Search Unity

Editor Event Listener Script

Discussion in 'Immediate Mode GUI (IMGUI)' started by Wattosan, Sep 6, 2018.

  1. Wattosan

    Wattosan

    Joined:
    Mar 22, 2013
    Posts:
    460
    Hey,

    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.

    Thanks!
     
  2. Johannski

    Johannski

    Joined:
    Jan 25, 2014
    Posts:
    826
    EditorApplication.playModeStateChanged is the event you're looking for: https://docs.unity3d.com/ScriptReference/EditorApplication-playModeStateChanged.html
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3.  
    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.     }
    13.  
    14.     private static void LogPlayModeState(PlayModeStateChange state)
    15.     {
    16.         Debug.Log(state);
    17.     }
    18. }
     
  3. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    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.