Search Unity

  1. Unity 2019.1 beta is now available.
    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. We're looking for insight from anyone who has experience with game testing to help us better Unity. Take our survey here. If chosen to participate you'll be entered into a sweepstake to win an Amazon gift card.
    Dismiss Notice
  4. On February 28th the Feedback website will shut down and be redirected to the Unity forums. See the full post for more information.
    Dismiss Notice
  5. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  6. Unity 2018.3 is now released.
    Dismiss Notice
  7. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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.