Waiting for Destroy to complete

Hello,

I’m trying to destroy several GameObjects, but I have scripts which access these GOs in their Update functions, leading to MissingReferenceErrors, and things not working as they should.

I tried using DestroyImmediate, but as expected (due to the recommendations against it), that caused other errors.

I thought that using yield with my function which does the destruction might help; but either it didn’t, or I don’t understand how yield works.

Is there a way to stop Updates from running while my GOs finish being destroyed? I’ve thought about wrapping the contents of the Updates in an if statement, but that seems like the wrong way to go about it.

Thanks in advance for any help.
Andrew

Um, is it perhaps so that other objects are referencing the objects that you are removing?

Basically what I learned from destroying is this:

If you call Destroy(gameObject), the gameObject will be destroyed at the end of the frame (or is it at the end of the update for that object?). That means that your script that called Destroy should still be able to execute the current Update function. If you have other objects referencing the object being removed, you should expect to either:

A) Be able to reference the objects the same frame, but not after that.

B) Not be able to reference the objects the same frame.

either case, you could probably do a if (myReference == null) and return early if they are unless you can manage to execute the script without those references.

In unity, references become null if the objects are destroyed automatically.

Thanks for the reply.

I’ve tried setting the references to the GameObjects in other scripts to null, but that doesn’t seem to be helping.

I’ve also tried setting the GameObjects themselves to null after destroying them (I remember reading in this forum about having to do this), but that throws ArgumentNullException: Argument cannot be null.

I should also add that the GOs that I destroy, I’m replacing with others I instantiate right afterwards, however the scripts still seem to reference the old GOs (even when I’ve set those references to null!).

I must be doing something wrong, but I’m not sure what. Any other ideas?

Andrew

Sounds like you’re trying to use the references after you set them to null.

You need to check your references every time you use them if they are null. Dont try to call functions or read variables on null references.

Example:

if (collider != null)
{
  // Safe to use collider
}

It is hard to pinpoint your exact problem without any source code to look at.

In case you have a scenario where script “A” requires references to other object that you delete, you need to rebind the references to valid objects (like new instances you create), or make sure that script “A” expects and handles missing references, or you are forced to destroy script “A”.