Is using #if UNITY_EDITOR return instead of #if !UNITY_EDITOR, to be able to see references in the code editor, a good idea?

Viewed 1271

I'm working on a existing mobile app. There are some occurrences like this:

private void Example()
{
    //some universal code
#if UNITY_EDITOR
    return;
#endif

#pragma warning disable CS0162 // Unreachable code detected
    //some mobile platform code
#pragma warning restore CS0162 // Unreachable code detected
}

I would have implemented it in the past like this:

private void Example()
{
    //some universal code
#if !UNITY_EDITOR
    //some mobile platform code
#endif
}

The UNITY_EDITOR version looks very ugly and I'm not able to add universal code at the end of the function. On the other hand it has the advantage to be able to find references to the mobile code when working in the Editor.

Is there anything I'm missing? Is there the possibility to change Visual Studio so it finds references and I have code highlighting in !UNITY_EDITOR code?

1 Answers

You're right, this does look fairly ugly. In my projects, I send to keep a file that defines platform settings, and I would leverage that here like so:

public static class ApplicationSettings
{

#if UNITY_EDITOR
        public static bool IsUnityEditor = true;
#else
        public static bool IsUnityEditor = false;
#endif
#if PLATFORM_STANDALONE_WIN
        public static bool IsPlatformStandaloneWin = true;
#else
        public static bool IsPlatformStandaloneWin = false;
#endif
... etc ...
}

Then, if your codebase really does do specific things based on platform, branch on that conditional.

public void Example()
{
    if (ApplicationSettings.IsPlatformStandaloneWin)
        StandaloneWindowsExample(); // windows specific
    else
        EveryoneElseExample(); // other platforms:

    ... // code that applies to all platforms 
}

Or even define your own enum for the platforms you support and switch on the value of that.

Related