Lesson 105 +10 XP

Platform-Dependent Compilation

Platform-dependent compilation allows you to write code that only compiles for specific target platforms, avoiding compiler errors from platform-specific APIs.

Platform Defines

Unity pre-defines specific preprocessor symbols:


csharp
void Start()
{
#if UNITY_EDITOR

### Debug.Log("Running inside the Unity Editor");
#elif UNITY_ANDROID

### Debug.Log("Running on Android device");
#elif UNITY_IOS

### Debug.Log("Running on iOS device");
#elif UNITY_WEBGL

### Debug.Log("Running in a WebGL browser context");
#else

### Debug.Log("Running on another platform");
#endif
}

Common Built-in Symbols

  • UNITY_EDITOR: Defined only when running inside the Unity Editor.
  • UNITY_STANDALONE: Target is a desktop platform (Windows, macOS, Linux).
  • UNITY_ANDROID / UNITY_IOS: Target is a mobile platform.
  • DEVELOPMENT_BUILD: Defined when building with the "Development Build" option enabled.

Guarding Editor Code

Any script referencing the UnityEditor namespace must be guarded with #if UNITY_EDITOR or placed in an Editor folder, otherwise compilation will fail during build generation:


csharp
#if UNITY_EDITOR
using UnityEditor;

public class CustomBuildTool
{
    public static void PerformBuild() { }
}
#endif

Custom Scripting Define Symbols

Define your own global preprocessor symbols:

  1. Open Project Settings > Player > Other Settings.
  1. Scroll to Scripting Define Symbols and add your symbol (e.g. ENABLE_DEBUG_MENU).

csharp
#if ENABLE_DEBUG_MENU

### ShowDebugButtons();
#endif

TL;DR

  • Use preprocessor directives (#if, #elif, #endif) for platform-specific API calls.
  • Always wrap UnityEditor namespace code in #if UNITY_EDITOR to avoid build errors.
  • Create custom compilation symbols in the Player settings.