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.

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 ( {
        print ("Script was disabled");
    else {
        print ("Object was destroyed or made inactive");