Destroy children seem not working

Hi guys, I’m troubling with this simple piece of code: can you help me please?

There is an Empty Object with some children attached. I’d like to delete them.

foreach (Transform child in GameObject.Find("EMPTYOBJECT").transform)
        {
            GameObject.Destroy(child.gameObject);
        }

foreach (Transform child in GameObject.Find("EMPTYOBJECT").transform)
        {
            Debug.Log(child.name);
        }

I’m expected that the second “foreach” doesn’t print anything, but instead it prints the name of the gameObject (that should be deleted)…

In the inspector EMPTYOBJECT has not children, but I got bugs in the following lines of code, because it seems the object are not really deleted…

Thanks!

Destroy is postponed to the end of the frame that is why you still see your guys because on the same frame you print their name and they still exist. Use DestroyImmediate if you absolutely need them off right away.

Destroy actually destroys the object after the Updates and before the frame is rendered. In this case, the children are still alive and kicking when the second foreach is executed - that’s why you still can print their names - but will not exist anymore by the next Update. There’s also the DestroyImmediate function, but it should be used only in Editor scripts.

hmmm, I tried DestroyImmediate:

foreach (Transform child in GameObject.Find("EMPYOBJECT").transform)
        {
            Debug.Log("delete: "+child.name);
            GameObject.DestroyImmediate(child.gameObject);
        }

It seems to work, partially… unluckily I’ve another bug: it destroys all the children of EMPTYOBJECT but not the last :frowning: whyyyy? :smiley:

Incredible:

 foreach (Transform child in GameObject.Find("EMPTYOBJECT").transform)
        {
            Debug.Log("name: " + child.name);
        }
 foreach (Transform child in GameObject.Find("EMPTYOBJECT").transform)
        {
            Debug.Log("delete: " + child.name);
            GameObject.DestroyImmediate(child.gameObject);
        }
 Debug.Log("FINISH");

I got this:

  • name: element_1

  • name: element_2

  • name: element_3

  • destroy: element_1

  • destroy: element_2

  • FINISH

And where is “destroy: element_3” ??? :frowning:

If i comment the line DestroyImmediate I got also “destroy: element_3”

Any ideas? :smiley: