MonoBehaviour.OnDestroy() how it works/ how to use it?

Hello guys!

I spent a lot of time understanding this function and I did many examples with this function but I didn’t reach anything conciliatory so I hope someone can help me.

My question is about uploading scenes:
Suppose I have a generic singleton that has this method in it.
Why should it has this method in it? I tested it and if I load a single scene the onDestroy function is called and that’s correct but if i delete this functin the program still works very good.

protected virtual void OnDestroy()
{
     Debug.Log("Destroyed"); 
    if (instance == this)
    {
        instance = null;
    }
}

This method makes sure the instance is not a object that is destroyed, which if you try to access will give you a different exception from trying to access a null object. Now i can’t answer why your program is still working fine after it’s deleted, i’d say it mostly depends on how you are implementing singletons, some implementations automatically create a instance of the object if they can’t find one on the scene, this is to make sure there is indeed one instance of this type on the scene.