Search Unity

  1. Check out the Unite LA keynote for updates on the Visual Effect Editor, the FPS Sample, ECS, Unity for Film and more! Watch it now!
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Editor Event Listener Script

Discussion in 'Extensions & OnGUI' started by F-R-O-S-T-Y, Sep 6, 2018.

  1. F-R-O-S-T-Y


    Mar 22, 2013

    I was wondering if anyone has an idea on how to create an editor script that listens to events such as when Play mode is entered or exited. The criteria is that it should not be something that lives in a scene. So no monobehaviours with DontDestroyOnLoad().

    I was thinking of something like a static class that is not instantiated in a certain scene.
    Is it doable with a scriptable object perhaps? It must be something that persists even after exiting play mode.

  2. Johannski


    Jan 25, 2014
    EditorApplication.playModeStateChanged is the event you're looking for:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    4. // ensure class initializer is called whenever scripts recompile
    5. [InitializeOnLoadAttribute]
    6. public static class PlayModeStateChangedExample
    7. {
    8.     // register an event handler when the class is initialized
    9.     static PlayModeStateChangedExample()
    10.     {
    11.         EditorApplication.playModeStateChanged += LogPlayModeState;
    12.     }
    14.     private static void LogPlayModeState(PlayModeStateChange state)
    15.     {
    16.         Debug.Log(state);
    17.     }
    18. }
  3. Madgvox


    Apr 13, 2014
    It's worth mentioning that there's no way inside of unity to make a non-serialized class truly persist through an assembly reload. The static class outlined by @Johannski is the way to go, but it's important to know that whenever the assemblies reload that class will be recreated from scratch, and all volatile data will be lost. If you need to keep some data persistent, you'll need to save it to EditorPrefs and restore it on reload.