Is there a way to know that Unity is quiting Play mode?

My scripts work just fine, but when I unpress Play more button in Editor I get a bunch of these errors:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

It comes from OnDisable method, so I assume that Unity has destroyed some object before the call to OnDisable of my script.

Is there a way to know that Unity is quitting Play mode? or workaround it in some other way…

You can get a callback for when the user presses the Play button (pause too) by registering to EditorApplication.playmodeStateChanged.

using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
public static class PlayStateNotifier
{
	
	static PlayStateNotifier()
	{
		EditorApplication.playmodeStateChanged += ModeChanged;
	}

	static void ModeChanged ()
	{
		if (!EditorApplication.isPlayingOrWillChangePlaymode &&
             EditorApplication.isPlaying ) 
        {
			Debug.Log("Exiting playmode.");
		}
	}
}

Alternatively you could just have a null check in your OnDisable before trying to access any other GameObjects.

I’m here in 2020. There are some changes in Unity 2019:

  1. EditorApplication.playmodeStateChanged is now obsolete and was renamed to EditorApplication.playModeStateChanged (capital “M”) and the event now has 1 parameter - PlayModeStateChange (see details here: Unity - Scripting API: PlayModeStateChange).

  2. Use the following updated code:

    using UnityEngine;
      using UnityEditor;
      
      [InitializeOnLoad]
      public static class PlayStateNotifier
      {
          
          static PlayStateNotifier()
          {
              EditorApplication.playModeStateChanged += ModeChanged;
          }
      
          static void ModeChanged(PlayModeStateChange playModeState)
          {
              if (playModeState == PlayModeStateChange.EnteredEditMode) 
              {
                  Debug.Log("Entered Edit mode.");
              }
          }
      }
    

I would suggest writing a couple of Utility methods:

  public static bool ApplicationIsAboutToExitPlayMode()
        {
#if UNITY_EDITOR
            return EditorApplication.isPlayingOrWillChangePlaymode && Application.isPlaying;
#else
            return false;
#endif
        }

        public static bool ApplicationIsAboutToEnterPlayMode()
        {
#if UNITY_EDITOR
            return EditorApplication.isPlayingOrWillChangePlaymode && !Application.isPlaying;
#else
        return false;
#endif
        }

And use them as following:

void OnDisable ()
{
    if (Utility.ApplicationIsAboutToExitPlayMode() == false) 
``{
             // Do your additional work here.
     }
}