Conditional compilation and UNITY_EDITOR
↑Quick overview
Section titled “Quick overview”The C# preprocessor can include or exclude code at compilation time. Unity defines symbols such as UNITY_EDITOR when compiling for the Editor. This lets you keep editor-only functionality out of player builds, but it is not a substitute for organizing editor tools into editor-only assemblies.
Correct syntax
Section titled “Correct syntax”Use #if UNITY_EDITOR, not #ifeditor or #if editor. UNITY_EDITOR is a symbol, and preprocessor directives use the #if ... #endif syntax.
using UnityEngine;
public sealed class EditorOnlyLog : MonoBehaviour{ private void Start() {#if UNITY_EDITOR Debug.Log("This message is compiled for the Unity Editor.");#endif }}Referencing UnityEditor safely
Section titled “Referencing UnityEditor safely”#if UNITY_EDITORusing UnityEditor;#endifusing UnityEngine;
public static class SceneHelper{#if UNITY_EDITOR [MenuItem("Tools/HCSTech/Print project path")] private static void PrintPath() => Debug.Log(Application.dataPath);#endif}UnityEditor APIs are not available in a normal player build. When making larger editor tools, place scripts in an Editor folder or an editor-only assembly rather than scattering many preprocessor conditions throughout gameplay code.
A safe workflow
Section titled “A safe workflow”- Decide whether the feature belongs to runtime code or editor tooling.
- Use a compile-time symbol for a small conditional section only when appropriate.
- Check both the Editor and the target player build, as a successful Editor run does not prove the build compiles.
- Keep editor-only dependencies behind an assembly boundary when the code grows.
See Assembly definitions for larger editor/runtime separation.
