top of page

#define POST_TITLE (Unity Conditional Compilation)

  • thetperson314
  • Aug 5, 2023
  • 2 min read

In this post we will learn to to use #define with #if in Unity to make your development process easier.


* If you already know to to use it jump to THIS BONUS PART where I show you how can use one variable for all the scripts in you project *



Why use it?

Conditional Compilation allow you to selectively include or exclude code from compilation, based on whether certain scripting symbols are defined or not defined.

That way, if you have a block of code you want to use or don't want to use if different situations you can do that without commenting your code!


Do to this simply use #define at the very top of your script



#define RUN_THIS_CODE

using UnityEngine;
using System.Collections;
public class PlatformDefines : MonoBehaviour
{ 
    void Start ()
    {
        #if RUN_THIS_CODE
            Debug.Log("This code is running");
        #endif
        
        #if !RUN_THIS_CODE
            Debug.Log("This code is not running");
        #endif
    } 
}

* As every other 'if' you also have an option for else - #elif / #else


Unity have already some pre-defined values we can use to check some states like



#if UNITY_EDITOR
#elif UNITY_IOS
#elif UNITY_ANDROID

For the full list check out THIS UNITY DOCUMENTATION


BOUNES PART


The problem with #define is that it's only for the current script, if you want to use it globally, with all scripts in the project you can do it from Unity.


1. Open Player Settings:

  • Go to the Edit menu in the Unity Editor.

  • Select Project Settings, then Player.


2. Define Symbol:

  • In the Player Settings window, scroll down to the Other Settings section.

  • Find the Scripting Define Symbols field.

  • Add ENABLE_FEATURE_X to the list of symbols. Separate multiple symbols with semicolons if needed.

For example, if the field initially contains:


UNITY;ENABLE_PROFILER;ENABLE_DEBUGGING

You can modify it to:


UNITY;ENABLE_PROFILER;ENABLE_DEBUGGING;ENABLE_FEATURE_X

Don't forget to apply the changes and now you can use this value in your scripts

 
 

Recent Posts

See All

FAVORITES

WHAT'S NEW?

The site is up and running, if let me know that you thing about it 😊

IN THE NEWS

I'm a paragraph. Click here to add your own text and edit me. It’s easy. Just click “Edit Text” or double click me and you can start adding your own content and make changes to the font.

CONTACT ME

Use any social media to contact me. For any question about programing and project I prefer using my Discord server

© 2021 by Amit Klein. Nerd Head.

bottom of page