unity crash when used destroy function

hello guys,
i started last week with my first little unity project.
so maybe my question might be quite stupid.

i tried to destroy my on runtime created game objects, when i restart my game. my code for this looks like:

while(GameObject.FindGameObjectsWithTag("testpoint").Lenght > 0){
Destroy(GameObject.FindGameObjectWithTag("testpoint"));
}

so my intention behind this was, to check if there are game objects with the tag “testpoint” and to destroy a random picked game object with this tag after this, until there arnt anymore.
this seems not to work and i cant figure out why. maybe i havnt understood some basics at this point.

i found a code example for this isue and it works fine:

GameObject[] testpoints = GameObject.FindGameObjectsWithTag("testpoint");
foreach(GameObject testpoint in testpoints){
Destroy(testpoint)
}

but why result my solution in a unity client crash?

thx for help :slight_smile:

Is the client hanging in an infinite loop?

If so, this will be (as I recently discovered :)) because the destroy does not actually happen until the next frame. Therefore, in the case of the foreach all items will be iterated over, destroyed and the code will continue on its merry way.

However, in the case of the while, the exact same object will constantly be returned and (re)destroyed. Hence the code will loop infinitely.

i guess so…

why will my while solution result in an infinitely loop? there is a fixed number of objects with this tag.
so if every while execution will destroy one object with:

Destroy(GameObject.FindGameObjectWithTag("testpoint"));

there wont be any objects left, after (in my case) ~30 while executions and the while loop will stop.

I explained it in my previous post. :slight_smile:

You could try removing the tag as well as destroying the object. That should also fix the problem for the while loop version.

1 Like

okay, i guess ur trying to tell me what ive found on the destroy documentation:
If obj is a GameObject it will destroy the GameObject, all its components and all transform children of the GameObject. Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.

right?
sorry if i have to ask multiple times, i want to understand my problem.

Yes, that is as I understand it.

The for loop is not affected because it is looping through all the GameObjects in one go but the while loop asks for the first object each time around and so is always getting the same object.

What you are trying to do now is:

  • Find all objects with the tag
  • Check if you found at least one
  • If that’s the case, find the first object with the tag
  • Destroy it.
  • Repeat

Even if it did work, it’s a bit of a crazy way to do it. You should be doing:

  • Find all objects with the tag
  • Destroy them:
GameObject[] testPoints = FindGameObjectsWithTag("testpoint");
foreach(var testPoint in testPoints)
    Destroy(testPoint);