- Home /
Call the destructor of MonoBehaviour.
Is there a function like Awake() that is called when an object/component is destroyed?
I am trying to make a small game, in which game objects are automatically instantiated or destroyed depending on the distance from the player. Every time objects are spawned they add them selfs to a global list (which is iterated in the main game loop), which is done in the Awake function. But I also have to remove them from the list when they are destroyed. Hence I need a way to detect when a class is being destroyed.
I have tried using the destructor of a class, but doesn't seem to fire up. Is there a default function enter code here
or something that is called when the instance of the class is being destroyed?
I don't want to do this when I call the function Destroy(), because it might lead to some messy lists, still having null references. And I have also tried checking for null references in the iteration, and calling the Remove function, but apparently it doesn't allow me to do this while iterating.
Answer by Eric5h5 · Feb 28, 2010 at 07:41 PM
Edit: Unity 3.2 has OnDestroy now, so the below is obsolete.
There's OnDisable, which works, although as you might expect from the name, it's also called if the script is disabled. You can work around that to some extent like this:
function OnDisable () {
if (gameObject.active) {
print ("Script was disabled");
}
else {
print ("Object was destroyed or made inactive");
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612090657im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
how to spawn and destroy 2 Answers
OnTriggerEnter - destroy (this.gameobject) if it collides with anything 2 Answers
How to emit particle from a collision? 2 Answers
Coding Gui Text To Perform After GameObject Destroy? 1 Answer