Just as the topic suggests, I would like to destroy a parent object after the children have all been destroyed themselves. I want this so that there isn’t a flood of empty gameObjects laying around the hierarchy. I tried using transform.childCount
to check the number of children an object has at the time it should be destroyed, but it didn’t work. Can your guys lend me a suggestion?
private void OnDestroy ()
{
if (transform.parent != null) // if object has a parent
{
if (transform.childCount <= 1) // if this object is the last child
{
Destroy (transform.parent.gameObject, 0.1f); // destroy parent a few frames later
}
}
}
@UnityCoach has provided a good answer, it will do the job under the condition that all, or at least the last child to be destroyed contains a component with this code.
However should your parent contain multiple different objects that do not all contain this script (and you don’t want to add N components into your scene one for each child to ensure this code runs) you can instead run this top down instead of bottom up, by which I mean add a single component (or append a script already on the parent) to check in its Update or LateUpdate if its childCount is 0. If it is, then all children regardless of type are destroyed and you are free to then self-destruct the parent object.