Search code examples
c#unity-game-enginegameobject

Destroy a GameObject in Hierachy that has no Children


I would like to make it so that in a script I can find out if an object in my hierarchy has a child and if it doesn't, destroy it. I would also like to know how in a script, create the same gameobject as one in my hierarchy, i.e. duplicate an object in my hierarchy.

I couldn't find anything on the sites.


Solution

  • Deleting objects that do not have a child

    You can create a script like this:

    public GameObject gm;
    
    if (gm.transform.childCount != 0)
    {
         // The object has a child.
         // Do whatever you want here.
    }
    else
    {
         // The object do not have a child.
         // Destroy the object.
         Destroy(gm);
    }
    

    If you want, you can even create a method that does that!

    public void DeleteObject(GameObject gm)
    {
        if (gm.transform.childCount == 0)
        {
            // The object do not have a child.
            // Destroy the object.
            Destroy(gm);
        }
    }
    

    Duplicating Objects

    About the "Duplicate Object", you can use this method:

     // You can call this method whenever you like and pass in the object that you want to duplicate.
     public void DuplicateObject(GameObject obj)
     {
          Instantiate(obj);
     }