Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Scripting' started by GhulamJewel, Jan 23, 2015.

  1. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    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.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Have each child report to the parent in OnDestroy.

    Check transform.childCount to see how many children are left
     
    Chickenbob5 likes this.
  3. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    Thank you for the reply. Do I do something like this

    attach this to parent

    Code (CSharp):
    1. Void Update () {
    2.  
    3.   if (transform.childCount > 0) {
    4.  
    5. destroy (gameObject);
    6.  
    7.    }
    8. }
    9.  
    and maybe attach to childs something like this

    Code (CSharp):
    1. void onDestroy() {
    2.  
    3. destroy(transform.parent.gameObject);
    4.  
    5.     }
    6.  
    7. }
    not very good am I haha please advise thank you.
     
    Chickenbob5 likes this.
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Your first script will do it all on its own. I was thinking of something like this, which is slightly more efficient.

    Code (CSharp):
    1. public class MyParentObject () {
    2.     public void CheckForDestroy (){
    3.         if(transform.childCount <= 0){
    4.             Destroy(GameObject);
    5.         }
    6.     }
    7. }
    8.  
    9. public class ChildObject (){
    10.     void OnDestroy (){
    11.         transform.parent.GetComponent<MyParentObject>().CheckForDestroy();
    12.     }
    13. }
    For ultra modularity you should have MyParentObject use AddComponent<ChildObject> 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.
     
    GhulamJewel likes this.
  5. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    Thank you very your guidance and advice. Both ways worked great :)