- Home /
Why is my MonoBehaviour never being deleted?
I discovered this problem because I have a script that hooks to a static event from another class. And noticed that after reloading a level, the event delegate function was being called TWICE; once for the new instance and once for the old instance.
After digging a bit further, I found that Awake(), Start() and Update() were not being called for the old instance. Although OnDestroy() IS called, every time the level is re-loaded.
I could even reproduce the issue with an empty game object with a single empty script:
public class EmptyScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnDestroy() {
}
}
Does anyone have any idea what's going on? I am thoroughly stumped. Everything I've read indicates that all objects are deleted when a new level is loaded. Yet clearly that's not happening. And no, I'm not using DontDestroyOnLoad anywhere.
Have you tried to release the subscriber? Actually, you may passing a static method to your event since you would get a null reference.
Simply, when you load the new scene, just clear the event:
OnEvent = null;
Or from other classes:
$$anonymous$$yClass.OnEvent -= $$anonymous$$ethodName;
I tried that, fafase. And although that prevents the method from being called twice, it doesn't result in the object being deleted. And still results in OnDestroy being called multiple times.
Later I even took out the static event business altogether, and that didn't change anything.
Also, remember: I see the SA$$anonymous$$E behavior with an empty GameObject with an empty script. So I think I have a more fundamental misunderstanding of the GameObject/$$anonymous$$onoBehaviour life cycle.