I have two scripts (X and Y) attached to a missile object. The Y script destroys the object once it collides with another object. But apparently, the Update of script X still gets called (I assume it happens only for one frame, if I read the Destroy documentation correctly). This gives me this exception:
MissingReferenceException: The object of type 'X' has been destroyed but you are still trying to access it.
In script X, I have tried to put in this line:
if(gameObject == null)
{
return;
}
But it still gives me the same error (at the very point where I do the check).
I have also tried to do a DestroyImmediate, but then I get this exception when the object collides:
Destroying object immediately is not permitted during physics trigger and contact callbacks. You must use Destroy instead.
I can see how I can use a boolean (set in Y, tested in X) to get the behaviour I want but this seems so messy. In particular, I will have to add this check in every script that I attach to the missile...and that seems really silly.
Am I missing something? Is there a proper way to get objects destroyed and prevent any updates in attached scripts?
Edit: The actual update method was in fact not called. The code that was called was a regularly scheduled event (and not scheduled through Invoke, but our own scheduler). The schedule was not canceled when the object was destroyed, so the code was hapilly called by the scheduler. :*|