Destroy object last on application close.

Hello,

I have a singleton object, GameManager, which maintains a list of all the GameObjects in the scene for faster access.

When an object is destroyed it calls,

GameManager.Instance.deregisterObject(gameObject)

however, this will obviously throw a NullReferenceException if GameManager has been destroyed. Is there any way to control the order in which objects are destroyed such that GameManager is the last to go or is there nothing to do but catch the NullReferenceException?

I’m aware of this solution: http://answers.unity3d.com/questions/670036/having-a-gameobject-get-destroyed-last.html but that isn’t exactly what I want as I would lose functionality that exists in GameManager.

I had this exact same problem! The singleton pattern kinda breaks when you can’t control when the instance is destroyed (which you would expect Unity to support, since they went to trouble of allowing custom initialization order). I just implemented this solution, which I rolled into my existing “BetterMonoBehaviour” class:

    protected bool applicationQuit = false;

    public void OnApplicationQuit() {
        this.applicationQuit = true;
    }

    public void OnDisable() {
        if(!this.applicationQuit)
            this.OnDisableBeforeQuit();
    }

    public virtual void OnDisableBeforeQuit() { }

    public void OnDestroy() {
        if(!this.applicationQuit)
            this.OnDestroyBeforeQuit();
    }

    public virtual void OnDestroyBeforeQuit() { }

When you derive from this class you just do

    public override void OnDestroyBeforeQuit() {
        GameManager.Instance.deregisterObject(gameObject);
    }

I also massively dislike the fact that OnEnable() is called before Start(), which makes it difficult to to share OnEnable() for initial setup and re-initializing after being disabled. Therefore I created OnEnableAfterStart() in the same way as above.