Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Conditional Unity Code?

Discussion in 'Editor & General Support' started by madGlory, Nov 24, 2022.

  1. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    44
    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:
    4,973
  3. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    44
    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:
    4,973
    The if unity is 2017 or newer basically is all unity versions, right? 2019 isn't even getting updates anymore
     
    madGlory likes this.
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    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.