Calling DestroyImmediate on Children of GameObject is behaving weirdly?

Hey there!

I’ve got a script running that generates a distribution of GameObjects on the click of a button and another button that is supposed to remove those generated objects. I use some Editor-Scripts to generate the objects while I’m not in PlayMode. Now I’ve noticed some weird behaviour, as not all of the generated objects get removed at once, just a subset of the objects. This is the script I use:

private void ClearObjects()
    {
        Debug.Log($"I have {transform.childCount} children");

        // Doesn't remove all child objects
        // for (int i = 0; i < transform.childCount; i++)
        // {
        //     DestroyImmediate(transform.GetChild(i).gameObject);
        // }
       
        // behaves exactly the same
        foreach (Transform child in transform)
        {
            DestroyImmediate(child.gameObject);
        }
       
        Debug.Log($"Not anymore! I have {transform.childCount} children now.");
    }

It seems that roughly the half of the children are being destroyed on each function call. Here is the Console-Log:
7850943--996048--upload_2022-1-29_13-40-23.png

I expected all the children to be removed. Is there something I’m missing?

“Destroy is always delayed (but executed within the same frame).”

Also note that it says “In game code you should use Object.Destroy instead.”

1 Like

See the link @RadRedPanda provided, although not for the explanation he gave. You need to read this part:

Try something like this:

while(transform.childCount > 0)
{
    DestroyImmediate(transform.GetChild(0).gameObject);
}
3 Likes

Indeed, but that doesn’t explain why only half of the objects are destroyed.

Yes, but since this isn’t executed in PlayMode, DestroyImmediate is the only option I have. Object.Destroy works only in PlayMode and DestroyImmediate always executes.

Works like a charm, thank you <3

Good catch! I somehow didn’t read the most important part.

If I were to take a guess, It iterated over the list sequentially. If you iterated over an array or list while removing every element, you would skip over every other one. For example, say you had an array of 5 elements, looping through and deleting using for(int i=0; i<array.Length; i++)

You remove the at element 0, and then the iterator moves to 1. However, since you removed the first element, the entire array shifts down, and what used to be at element 1 is now at element 0. This results in it removing elements 0, 2, and 4.

1 Like