Script on a destroyed GameObject still accepting event callbacks?

I have a script attached to a GameObject which does the following:

  • Determines a target GameObject and stores its ‘entity’ script in currTarget
  • Subscribes to the onDeath event of currTarget
  • Attacks currTarget
  • Calls Destroy(gameObject) when dead.

Now, let’s say I have three GameObjects with the ‘entity’ script attached to them, A, B, and C. A is an enemy of both B and C. A’s current target is B, and both B and C target A.

A kills B, so B Destroy()s itself and fires its onDeath event (captured by A). Many frames later, C manages to kill A, so A fires its own onDeath event. What happens now is this event is captured by both C (still alive) and B (supposedly destroyed).

Strangely enough, this test if statement actually passes as true (and the Debug message is displayed):

if (this == null)
		Debug.Log("I should be dead!");

…so how can something that is null execute in the first place?

Am I missing something here? It seems very strange that scripts should still be running if their parent GameObject has been destroyed.

In OnDestroy function unregister the even handler

for example :

_EventDelegate+=function;  //Registering 
_EventDelegate-=function;  //unregister..

this would avoid these confusions

Check out: c# - How to correctly unregister an event handler - Stack Overflow

(y) to flamy

Also a good idea is to have functions for registering your object to all events you need and another for the opposite and call them at correct times.

Ie if you want to deactivate gameobjects but want them to continue listening to events in case they are reactivated then call the UnRegisterAllEventsINeed function upon deactivation so that the eventhandler doesn’t try to call the function from the deactivated object any more and call RegisterAllEventsINeed inside OnEnable and accordingly UnRegisterAllEventsINeed inside OnDisable to automate the process.Anytime you deactivate them you also take them off the listener list and when you reenable them they get back on the listener list.