- Home /
Destroying all child objects.
When attempting to destroy an instance of a game object that has multiple child objects, the object remains visible on the screen unless I do the following:
private void ScheduleForDesruction(Rigidbody gameObject, float time)
{
foreach(Transform xform in gameObject.transform)
{
Destroy(xform.gameObject, time);
}
Destroy(gameObject, time);
}
Even then, there is an audio source gizmo that remains visible on the Scene view screen. Everything I've found here in the wiki regarding this indicates that calling Destroy on a game object effectively destroys all the children. This doesn't happen in my case. In fact, if I don't iterate through the entire transform array as above, the object remains visible on the screen.
Is there something I need to do differently here? Perhaps when the object is a Rigidbody, Destroying it requires different treatment? ... or when there's an audio source attached, does it have to be deleted individually?
Answer by efge · Mar 15, 2011 at 03:32 PM
Destroy(gameObject, time); in your script destroys only the component Rigidbody not the game object itself (because your variable gameObject is of type Rigidbody).
Thanks. I just checked it out. The following code does work...
Destroy(gameObject.gameObject);
I had assumed a Rigidbody was equivalent to a gameObject in this regard. $$anonymous$$uch appreciated.
... or you could change your first line to "private void ScheduleForDesruction(GameObject gameObject, float time)"
No, gameObject is always the reference to the containing GameObject. If you destroy the GameObject all containing Components and child GameObjects should be destroyed as well.
oh, sorry, i just saw that he named the parameter of his function gameObject.... :D. In this case you're absolutely right.
It's not good practise to hide inherited variables or properties as it leads to such errors or confusions.
Answer by Pi_3.14 · Sep 30, 2012 at 01:51 PM
Courtesy of Zerot on the IRC channel:
0,1,2,3,4
loop: index = 0 : ->0,1,2,3,4 Destroy:
contents shift: ->1,2,3,4 index++
because of loop: 1,->2,3,4 index = 1
Destroy: contents shift: 1,->3,4
index++separate array/list loop: index = 0 :
->0,1,2,3,4 Destroy: no content shift because of separate array: ->0,1,2,3,4
index++ because of loop: 0,->1,2,3,4
index = 1 Destroy: no content shift
because of separate array: 0,->1,2,3,4
Basically you can't remove elements while inside a fast enumeration, otherwise it will miss alternate elements.
Your answer
![](https://koobas.hobune.stream/wayback/20220613113001im_/https://answers.unity.com/themes/thub/images/avi.jpg)