Reach Scripting Define Symbols in Runtime

Is there a way to list the “Scripting Define Symbols” in runtime? I know I can reach them through EditorUserBuildSettings.activeScriptCompilationDefines but I need a runtime version of it.

Alternatively I can also use a similar field in my own scripts, if the above is not possible, how can I parse a string as a preprocessor directive? I know that #if “some_string” wouldn’t work. How does Unity #define those strings in the background anyway?

To provide some background info, what I want to do is, I want my script to delete the object if some preprocessor condition is met. And I want to assign those conditions through the Inspector. Like below.

public string[] conditions;
void Awake() {
#if conditions
     Destroy(gameObject);
#endif
}

Defines are a pure compiler feature, they don’t exist at runtime so there is no way to query them.
One “automated” way to get them at runtime would be to use EditorUserBuildSettings.activeScriptCompilationDefines and generate a cs file like

public static string[] RuntimeDefines = new string[]{
#if DEFINE_A
"DEFINE_A",
#endif
...
}

which is then compiled into the project.

if you want to enable/disable features at runtime you cannot use #if as this would exclude the code from ever being included. For your case a normal if() statement will work ok.

As for how Unity does these defines: They are passed as commandline arguments to mcs.exe.

2 Likes

Thanks for the great explanation, much appreciated.

A better way (IMO) to accomplish this would be to use a conditional function.

In the below code, the function BuildSpecific_ConditionalDestroyObject() is only compiled into the final executable if the symbol “conditions” is defined, otherwise the function call does nothing.

using System.Diagnostics;

void Awake()
{
    BuildSpecific_ConditionalDestroyObject()
}

[Conditional( "conditions" )]
void BuildSpecific_ConditionalDestroyObject()
{
     Destroy( gameObject );
}