[Solved] How To Destroy Parent Object After Child Are Destroyed?

Hi there. Simple question I presume. How would I go about destroying parent object after child are destroyed.

e.g

Parent

  • Child
  • Child2

I am making a two player game but want to call some scripts only when both players dead. So I thought I attached them on the parent and the parent only gets destroyed after both child are dead and so the scripts will be called. Please advise. Thank you.

Have each child report to the parent in OnDestroy.

Check transform.childCount to see how many children are left

1 Like

Thank you for the reply. Do I do something like this

attach this to parent

Void Update () {

  if (transform.childCount > 0) {

destroy (gameObject);

   }
}

and maybe attach to childs something like this

void onDestroy() {

destroy(transform.parent.gameObject);

    }

}

not very good am I haha please advise thank you.

1 Like

Your first script will do it all on its own. I was thinking of something like this, which is slightly more efficient.

public class MyParentObject () {
    public void CheckForDestroy (){
        if(transform.childCount <= 0){
            Destroy(GameObject);
        }
    }
}

public class ChildObject (){
    void OnDestroy (){
        transform.parent.GetComponent<MyParentObject>().CheckForDestroy();
    }
}

For ultra modularity you should have MyParentObject use AddComponent during the start function. This means the children do not have to know they are being tracked, and will continue on their merry way. I use a similar concept in my object pool.

1 Like

Thank you very your guidance and advice. Both ways worked great :slight_smile: