Skip to main content
Updated date:

How to Remove a Child From a Parent in Unity

Author:

The child-parent relationship in Unity is pretty handy, and allows you to effect changes to multiple objects by messing with only the parent of those objects. Occasionally, though, you may want to remove a child from a parent, and it's a trickier task than it sounds. There are a few ways to get it done.

Screenshots taken by myself. Unity owned and developed by Unity Technologies.

Screenshots taken by myself. Unity owned and developed by Unity Technologies.

Method 1: Remove From Hierarchy

The simplest, most obvious method for separating child from parent is via the Hierarchy. In the above example we have BoxParent, the parent, and HubGuyPink, the child. Click on HubGuyPink and drag the GameObject to an empty space in the Hierarchy. Both parent and child will become independent GameObjects again. Easy peasy. Deleting the child GameObject will also make the parent GameObject independent.

This method cannot be used during runtime, of course, and in basically every other case children need to be removed from parents via scripting.

Method 2: Remove All Children

The second way to remove child GameObjects from a parent is to use either a loop or a function to detach every child from the selected parent. We'll use a loop first.

In theory this first method should only require one loop, and depending on your version of Unity it may work. If it does not, this double-loop method will do the job just fine:

public class DetachChildren : MonoBehaviour {

    public GameObject parentObject;
    public GameObject newParentObject;

    private void Update()
    {
        while (parentObject.transform.childCount > 0)
        {
            foreach (Transform child in parentObject.transform)
            {
                child.gameObject.transform.parent = newParentObject.transform;
            }
        }
    }
}

Here we have the parentObject, which contains the children, and the newParentObject, where we're going to send the children. When we hit the L key the script will check if parentObject has more than zero children. If it does it will run a foreach loop that checks each Transform attached to parentObject - the Transforms of the children - and sets their parent to newParentObject. If you want you can also substitute in either destroying the child object or simply setting its parent to 'null', which turns the children into independent GameObjects.

Note that this method is overcomplicated and the result of a possible bug in older versions of Unity which skips every other child. Ideally only the foreach statement is necessary to get the job done.

Your other option here is to use a function, which is simpler and cleaner than loops. In this case the function you want, DetachChildren(), is built right into Unity. Type in the following code:

  private void Update()
    {
        if(Input.GetKeyDown(KeyCode.L))
        {
            parentObject.transform.DetachChildren();
        }
    }

And voila! All of the child GameObjects are made independent on the parent when you hit the L key. Note, however, that this function only allows you to remove children. If you want to destroy or relocate children to another parent you'll need to use a loop.

Method 3: Remove Specific Children

Things get a little more complicated when you want to remove a specific child from a parent. In order to get this done you'll need to provide Unity with information that will allow the program to ID and manipulate the child in question. The most straightforward method is to have Unity look for the name of the GameObject:

 if (Input.GetKeyDown(KeyCode.L))
        {
            Transform childToRemove = parentObject.transform.Find("HubGuyPink");
            childToRemove.parent = null;
        }

Here we set a new Transform, childToRemove, and order Unity to Find the object with the specific string "HubGuyPink" as its name. Then we set childToRemove's parent to 'null'. This removes the HubGuyPink GameObject from parentObject. It is generally not a great idea to hardcode a text string like "HubGuyPink" directly into your scripts, of course, so you'll want to declare a string variable to take the place of the text in the code, like so:

 public string itemToRemove;

if (Input.GetKeyDown(KeyCode.L))
        {
            Transform childToRemove = parentObject.transform.Find(itemToRemove);
            childToRemove.parent = null;
        }

Getting the name of a GameObject is often clumsy and imprecise, however, and you may want a different method for targeting specific children. In this case you may want to look for children with a specific component attached instead.

 private void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
            ShieldScript shieldToRemove = parentObject.GetComponentInChildren<ShieldScript>();
            shieldToRemove.gameObject.transform.parent = null;
        }            
    }
}

This example assumes that one of the children attached to the parent has a script component attached to it named 'ShieldScript'. When L is pressed this code creates a new local variable, shieldToRemove, and looks for the first child in parentObject with that script attached. In the next line it then sets the parent of that child to null, making it an independent GameObject, though per usual you could destroy or re-locate the child instead. Note that this only sets the first GameObject Unity finds as shieldToRemove, and will ignore any others that fit the criteria.

Looking to remove several specific children at once? Your script will look a little different, but it's a simple change:

 private void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
                foreach (Transform child in parentObject.transform)
                {
                    if(child.GetComponent<ShieldScript>())
                        {
                            child.parent = null;
                        }
                }                       
        }            
    }

Here Unity will check parentObject for any children that have the ShieldScript component attached. If any children fulfill that criteria they will be turned into independent GameObjects.

One Final Note About Children

It's worth knowing that alongside removing children you can also alter children using essentially the same programming methods. If, for example, you wanted to add a component to children that only have ShieldScript attached, you could change 'child.parent = null' to, say, 'child.gameObject.AddComponent<NewScript>()'. This will then add NewScript to each of the children that fulfill the ShieldScript criteria. You could even do that and then remove the child, signifying some sort of change after the child is detached.

Related Articles