How to detect in OnDestroy if scene is closing/game is being closed

Hello,

I have a question if there is a way to detect in the OnDestroy() function if the object is destroyed because the level is closing/game is closing.

I have an object (soldier) that is spawning other objects in some situations (health-bar etc.). In the soldier’s OnDestroy() I also remove all objects that the soldier spawned (soldier keeps references). The code looks like this:

class Soldier{

    Transform m_CreatedObject = null;

    public void Updade()
    {
       if (something)
           m_CreatedObject = Instantiate(something);
    }

    public void OnDestroy()
    {
       if (m_CreatedObject  != null)
          Destroy(m_CreatedObject);
    }

}

When I close the editor I get the MissingReferenceException because Unity destroyed the m_CreatedObject before Soldier object when the game is closed. What can I do in this situation?

No, there isn’t- but that’s why the

void OnApplicationQuit()
{
    // do stuff here!
}

callback exists! Use this to destroy the sub-elements before the game would close, preventing the OnDestroy problems from occuring.