How To Get All Of An Object’s Children – Unity C#

If you’ve ever wanted to get all of the children attached to a Unity GameObject and turn them into an array, there is a simple way to do it. The following code gets the jobs done, written in C#.

Transform[] allChildren = GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
    child.gameObject.SetActive(false);
}

Since each child has a Transform component, this code will get all of the children and convert them into an array of Transforms. It will then loop through the array and deactivate them all. Read more about foreach loops here.

Although it’s an array of transforms, you can see from the loop it’s easy to access the GameObject. If you wanted a list of GameObjects rather than Transforms, you could improve the code thus:

Transform[] allChildren = GetComponentsInChildren<Transform>();
List<GameObject> childObjects = new List<GameObject>();
foreach (Transform child in allChildren)
{ 
    childObjects.Add(child.gameObject);
}

If you have any questions, ask me in the comments below. Stay tuned to this blog for more programming and game development tips.

 

Advertisements

2 thoughts on “How To Get All Of An Object’s Children – Unity C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s