Search code examples
c#visual-studiounity-game-enginepreprocessor-directive

Renaming variables inside preprocessor directives in Visual Studio


I've got a convenience problem, where if I want something to be executed only on specific platforms, the compiler stops checking and refactoring the code. So in this scenario, if I refactor foo to bar in Visual Studio, it will only refactor the foo = true part to bar = true, but foo = false will not be changed.

bool foo;
#if UNITY_EDITOR
    foo = true;
#else
    foo = false;
#endif

To avoid that, in some cases I changed the code to

bool foo;
#if UNITY_EDITOR
    foo = true;
    return;
#endif
    foo = false;

but that is not only more tedious, because I have to make sure, that I can return after assigning something to foo, I also get a warning about unreachable code in the Unity Editor.

So my question is: What is the best way to handle this? Is it possible to make Visual Studio also code-check and refactor code that is not used for the current platform?


Solution

  • When the Preprocessor directive used(UNITY_EDITOR) used is true, the rest of the code in the #else and #elif statement is now considered as a comment.

    This has a simple fix in Visual Studio 2015 and above. When you rename avariable, check the Include Comments checkbox.

    enter image description here