Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Question Conditional Unity Code?

Discussion in 'Editor & General Support' started by madGlory, Nov 24, 2022 at 8:22 AM.

  1. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    39
    I would like to write some c# code that works with or without Unity. Is there some platform symbol that would check if the code is running in Unity?

    Ideally something like this:

    Code (CSharp):
    1. #if Unity
    2. using UnityEngine
    3. #endif
    4.  
    5. public class MyClass {
    6.    #if Unity
    7.    [SerializeField]
    8.    #endif
    9.    private int myInt;
    10. }
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    1,984
  3. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    39
    Thanks for the answer, but neither of these is really what I'm looking for.

    The platform dependent compilation symbols just give you options for Unity environments but I want to know if the script is in any of these without having to write all of them.

    Creating a custom symbol seems error prone and requires maintenance which I'm trying to avoid.

    Would love something automatic from within Unity to check if Unity is running.
     
  4. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    1,984
    The if unity is 2017 or newer basically is all unity versions, right? 2019 isn't even getting updates anymore
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    29,558
    Generally when you do this, you write the entire codebase to work without touching anything in the Unity namespaces.

    Obviously pretty much every way in and out of your codebase would need to be completely generic, such as supplying delegates for input/output.

    Then launch the codebase in two different ways, either with and without Unity, providing delegates for each way.

    Otherwise your code would be splattered everywhere with
    #if
    s... yuck.
     
    DevDunk likes this.
unityunity