- Home /
The question is answered, right answer was accepted
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;
}
}
Answer by Houtamelo · Nov 14, 2020 at 07:47 PM
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.
Thank you for your answer!(sorry if it's a little late)
Follow this Question
Related Questions
Extending a Singleton base class (UJS) (?) 2 Answers
MonoBehaviour pseudo-singleton with C# generics 1 Answer
MonoBehaviour Inheritance, Singletons and Generics 1 Answer
Singleton Toolbox compile error 2 Answers
Big problem with a small singleton 1 Answer