Home > database >  Create gameobject in the script with a variable
Create gameobject in the script with a variable

Time:01-16

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.

CodePudding user response:

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);
 }
  • Related