- Home /
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.
Answer by flamy · Feb 06, 2012 at 06:49 AM
In OnDestroy function unregister the even handler
for example :
_EventDelegate+=function; //Registering
_EventDelegate-=function; //unregister..
this would avoid these confusions
But if you register an anonymous lambda? How do you unregister that?
If it's a one shot event you can write the unregister call last in the lambda but if you want to have it consume events till you want to kill it then you should probably do named functions ins$$anonymous$$d of lambdas.
Other than that there's also _EventDelegate = null but that's not good if you want to remove only one listener/lambda.
Answer by $$anonymous$$ · Nov 23, 2013 at 12:50 AM
(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.