Variable C# compiler directives

I know about the C# compiler directives that allows you to compile code with platform specific functions (UNITY_ directives). But I’m wondering if and how I can make my own variable compiler directives.

Reason for asking is that I’m currently coding the d20 RPG system for Unity/C# and this RPG system comes with a HUGE amount of optional rules. Since I want this d20 RPG system to become a plugin on the asset store, I want the user of this plugin to tell the code if he wants to use certain parts of the optional rules or not.

I’ve googled the C# directives a bit amd I came up with something like this:

// #define OptionalRule1 // Will not use in this example
#define OptionalRule2

#if OptionalRule1
  //Well not using this one
#endif

#if OptionalRule2
  // Code for optional rule 2 is used
#endif

Is the above correct? With that I’d also like to know if the #define statements have to be used once in a scene or once per piece of code, or even if it’s to be used only in the code where the #if statement resides…

Yes, it’s correct. With assumption #define is in start of file (if they’re after any directives like “using” you will get compiler error).

Generally it depends on compiler. For Unity it’s:

  • To define them globally use Player Settings (Scripting Define Symbols) - that way Unity defines it in all scripts it compiles.
  • Otherwise it’s once per script (if you #define in the beginning of script, only same script has its #if resolved).

It’s checked at compile time only one time (when you click Build button to build project or when Unity reloads code) so it will never change between scenes/whatever else runtime.

Found where to add the option. Is there a way to let it add this information automated (check boxes or so) from the plugin?

Also, there’s only 1 line to define the symbols. Do I need to write #define OptionalRule1 or just OptionalRule1? And how to add multiple definitions? Separate with comma or just space?

Unity - Manual: Conditional compilation contains alternative way of defining globally in the very end - you should do it that way. Also there’s format for Scripting Define Symbols there - OptionalRule1;OptionalRule2;OptionalRule3 - as a picture.

Another way is writing Editor script that will modify PlayerSettings.

1 Like