Loading lessons...
Platform-Dependent Compilation
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:
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:
#if UNITY_EDITOR
using UnityEditor;
public class CustomBuildTool
{
public static void PerformBuild() { }
}
#endif
Custom Scripting Define Symbols
Define your own global preprocessor symbols:
- Open Project Settings > Player > Other Settings.
- Scroll to Scripting Define Symbols and add your symbol (e.g.
ENABLE_DEBUG_MENU).
#if ENABLE_DEBUG_MENU
ShowDebugButtons();
#endif
TL;DR
- Use preprocessor directives (
#if,#elif,#endif) for platform-specific API calls. - Always wrap
UnityEditornamespace code in#if UNITY_EDITORto avoid build errors. - Create custom compilation symbols in the Player settings.