OnDisable & OnApplicationQuit

In my latest project, I ran into an issue with OnDisable being fired when I stop the project running in the editor.  I’d get a host of errors about destroying transforms and not gameobjects.  Now I didn’t do any of that, but I did have an OnDisable routine that moved all the children of the disabled gameobject into a pool for reuse at a later point.

Turns out that all GameObject’s are disabled when you exit run mode in the editor, and they all have OnDisabled called one last time.  Not sure why this caused the error I was seeing and not even sure it was a real problem, but it was ugly seeing all those red exception errors fill my console window.

OnApplicationQuit to the rescue! After some googling I found that others have been having the same problem and it is a pretty simple solution.  Just add a private bool to your script and the Monobehavior method ‘void OnApplicationQuit()’ which just sets this bool to true.  Now in your OnDisabled method you can check to see if that bool is true & do nothing if it is!

OnApplicationQuit is called before the OnDisabled methods, so that flag gets set and your other methods just return. Simple & Clean!

private bool applicationIsQuitting;
void OnApplicationQuit()
{
	applicationIsQuitting = true;
}
void OnDisabled()
{
	if (applicationIsQuitting)
		return;
	Debug.Log("OnDisabled");
}

Leave a Reply