- Home /
Deleting GameObjects
I am presented with a situation where I need to delete all object under a GameObject.
I am unsure whether
Destroy(parent)
parent = new GameObject();
or
for (int j = children - 1; j >= 0; j--) {
GameObject.Destroy(parent.transform.GetChild(j).gameObject);
}
is more efficient. I think it all boils down to how Destroy is implemented. Does anyone know which is more efficient?
If efficiency is your concern then maybe you shouldn't destroy the objects in the first place. You can rather set them inactive and maybe reparent them to an inactive parent. Use an Object pool and reuse these objects without re-allocating them in the future.
I actually cannot use the same children, but i must recreate them on each frame, possibly less each frame.
Destroying something each frame is going to create a lot of garbage. When the garbage colllector kicks in you will get a frame dip. What prevents you from reusing them?
I am using a light clustering algorithm which is dependent on camera distance from light coordinates. Lights are being created as children of an entity after clustering occurs. The points clustered on the next frame may change and that is why i must delete all the children. This is actually part of a B Sc project.I can reuse the lights if the camera does not change in distance but for this project I must recompute the whole pipeline in order to show the worst case scenario fps.
Answer by Pengocat · Apr 10, 2017 at 02:15 PM
If you destroy a specific GameObject all of its children will be destroyed with it. You do not need to manually destroy individual children.
Destroy(gameObject);
so destroying the parent is more efficient, thanks.
On a micro level yes and it is also more readable and maintainable.