Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to know and control by script if it's runing in editor or within a build

Discussion in 'Scripting' started by Bennyman, Sep 11, 2023.

  1. Bennyman

    Bennyman

    Joined:
    Feb 9, 2016
    Posts:
    13
    Hello,

    I need to have separate behaviours when I execute code :
    1) within the Unity editor play mode is off
    2) within the Unity editor play mode is on (scene is running)
    3) within a build (outside the Unity editor)

    Is it possible ?
    I only know and use [ExecuteInEditMode] but it's not only executing in edit mode, but in all cases (1,2 &3).
    Is there a kind of "ExecuteInEditModeOnly" or ""ExecuteInBuildModeOnly" ?


    Also I'm using the "recorder" (video recorder) which is intended to be used only in the editor during play mode. This cause problem an error when I'm trying to do a build (The type or namespace name 'VideoRecorderManager' could not be found (are you missing a using directive or an assembly reference?). Is there a best practice to use such limited component?

    Thanks for your help !

    Ben
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,160
    You can easily redirect or conditionally compile in these situations with either
    #if UNITY_EDITOR
    pre-processor directives, or using something like
    Application.isPlaying
    or similar to determine what environment the code is running in.
     
  3. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    10,069
    As @spiney199 said, you can put your code in
    #if UNITY_EDITOR
    if you have a portion of code to run only in editor. But you have more possibilities: if you want something guaranteed only be in the editor, you can put the scripts in a folder called
    Editor
    or make it part of an editor-only assembly. Depends on the surrounding code, if they have to be in the built app or they are editor-only too.