Detect play mode stopping in [ExecuteInEditMode] script

I’ve got a number of gameobjects in my scene that support dynamic meshing in the editor as well as in my game at runtime. The behaviour they need to exhibit in each case is a little different, so I’ve been using Application.isPlaying checks to determine which state I’m in.

Now, things are fine until I stop a scene from play mode to return to the editor. In this case, I need to call an Init() function on some of my objects so that when they are reloaded in the scene that they don’t just break and start throwing exceptions (some of my objects that aren’t stored in public inspector variables are getting garbage collected, it looks like).

So the question is: Is there some way that I can – from an object in the editor – detect that the Unity engine just returned from play mode so that I can run some code to respond to that?

or for the intrepid individual…

Is there some way that I can preserve the state of my private non-inspector variables so that they don’t get garbage collected in the first place?

You can detect when the Editor changes playmodes with EditorApplication.playmodeStateChanged. It gets called twice for each change, once just before entering the next play mode, and straight after.

void OnEnable(){
#if UNITY_EDITOR
    EditorApplication.playmodeStateChanged += StateChange;
#endif
}

#if UNITY_EDITOR
void StateChange(){
    if (EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying)
}
#endif

The callback will get called twice, before changing modes and straight after, hence the if-clause. The callback will also be called on pressing the pause button. You might want to get a check for that too.

It’s also a good idea to unregister from the callback. OnDisable is a good place for that.

Furthermore, if this script is attached to a GameObject, you’ll need to use preprocessor directives to leave out all the UnityEditor calls. EditorApplication is in the UnityEditor namespace. I added them in my snippet, just in case.

My understanding of Unity’s serialization is that it doesn’t happen when moving from play to edit mode. You could get a custom serializer from the asset store that does this. You could also try to make one yourself using the playmode callback.