Facebook

Unity Scripting Essentials: Get Children of a Transform

by Michael Sacco Published August 22, 2023
The cover for Unity Scripting Essentials: Get Children of a Transform

The other day, I was putting together a demo scene for my low poly trees asset pack. This pack includes something like 40+ tree models. Each tree is a child of a single parent object that I called the Environment.

I wanted to make it easy to preview each tree when you download the assets into your project. So, I thought that it would be great to arrange them in a line. That way you can zoom around in the scene view to see each tree in isolation. I could set the position of each tree by hand. But, it would take a few minutes to arrange them.

Instead, I wrote a small script. This script gets all the children of the Environment parent transform. Then, it arranges the trees for me. I ran the script, it worked, and I saved myself a few minutes.

This experience inspired me to draft a short article. In this article, I will show how to get all the children of a transform in Unity. I wrote this article for a beginner game developer. If you are new to Unity, this is the article for you. If you are a Unity pro, keep reading! You might learn something new.

In this article, I will give a high-level overview of the Unity hierarchy system. I’ll explain how to use Transform.GetChild(). I’ll provide an example of how to iterate through the children in your scene. And, I’ll share a useful helper script that works like a GetChildren method in your project.

If you’re looking to go the other way, consider learning about the GetComponentInParent method.

What you need to know about transform children

  • The hierarchy describes how objects relate to one another. Each game object can have one parent. Each game object can have an infinite number of children.
  • Use Transform.GetChild() to get a specific child of a parent.
  • To iterate through children, use a for loop with .childCount and .GetChild().

Important methods and properties for transform children

transform.GetChild(int index) returns a specific child transform by index.

transform.childCount returns the number of children associated with the transform.

GetChildren Unity extension method

I wrote a lightweight helper method to get all the children of a transform. You can copy and paste this into your project. Then, you will call it to get a list of the children of the transform.

Add this class as a new c# script in your project.

using System.Collections.Generic;
using UnityEngine;

public static class GetChildrenExtension
{
  public static void GetChildren(this Transform parent, List<GameObject> children)
  {
    foreach (Transform child in parent)
    {
      children.Add(child.gameObject);
      child.GetChildren(children);
    }
  }
}

When you call this extension method, you get all the children of the parent transform. Of course, if you are not familiar with extension methods, you might not be sure how to use it. That’s why I also made an example script.

P.S. For the curious, this extension method uses recursion.

How to use this extension method?

I wrote an example script to show how you would call this extension method. Add this script to a parent object with more than one child object. Then, enter play mode. The script will write the name of each child object to the console.

Here’s an example of how you would call this extension method:

using System.Collections.Generic;
using UnityEngine;

public class GetChildrenExample : MonoBehaviour
{
  private void Start()
  {
    List<GameObject> children = new List<GameObject>();
    transform.GetChildren(children);
    foreach (GameObject child in children)
    {
      Debug.Log(child.name);
    }
  }
}

So, that’s the introduction. Keep reading for a comprehensive review of basic Unity concepts. You will learn what the hierarchy is. You will learn how to use Transform.GetChild(). And you learn how to use the transform foreach iterator to get the children of a transform.

What is the Unity hierarchy?

Before we dive in, let’s understand the concept of hierarchy in Unity. Unity lists each GameObject in your scene in the Hierarchy window. Note that these are not returned like a c# dictionary with key-value pairs but are unordered, like a c# list.

You can drag and drop GameObject A into another GameObject, GameObject B, in the hierarchy.

  • When you do this, you make GameObject A the child of GameObject B.
  • At the same time, you are making GameObject B the parent of GameObject A.

You can also configure hierarchy using the scripting API. But, that is too technical for this article.

💡 Remember:

  • A child can have one and only one parent.
  • But, a parent can have many children. Just like real life.

Does it matter if my object is a child or not?

The parent-child relationship has a large impact on how your child moves in the scene.

Imagine that you are a parent. When you move to a new city, you take your child with you, right? It works the same way in Unity. When a parent moves, all its children also move. If the parent transform changes, that change also applies to the children. We say that the child inherits the transform of the parent.

In some cases, this is great. If you want to make your game in first person, all you need to do is make your camera a child of your character. If your character moves or turns, the camera will, too.

In other cases, this is not what you want. If you want to make your game in third person, you want smooth camera movement. To do that, you need to separate your camera from your character. Then, you can use scripting for the camera. You can make the camera smoothly follow your character’s view direction and position.

You must understand the Unity hierarchy system. And, you must understand how the parent-child relationship works. This is a basic Unity concept that you need to clearly understand if you want to make a game.

The hierarchy is important for a variety of reasons. I’ll list out some of them here:

Organize Your Scene

If you want to create a well-structured and manageable scene, you need to maintain your hierarchy. When your hierarchy is neat and organized, your project will be easier to manage.

Manage Complex Interactions

You can use the transform inheritance property to your advantage. If you want an object’s position or rotation to depend on another object, you can use the transform hierarchy to make your life easier.

How to use Transform.GetChild()

Unity provides a simple method to get a single child of a Transform.

transform.GetChild(int index);

This method allows you to get a specific child. The child that you get is based on the index. The index represents the position of the child in the list of children objects. This is the exact same list you see in the hierarchy.

⚠️ Warning!:

  • GetChild only returns the first level of children. It does include children of children.

Using Transform.GetChild() in practice

In this section, I’ll show you how to actually use GetChild in a real-world scenario.

Imagine that you are making a side-scrolling platformer game. In your game, the player controls a character. The character needs to navigate through different levels.

In one of the levels, there’s a complex mechanism composed of interlocking gears. Each gear is a separate GameObject. These interlocking gears rotate. To set this up, you created some Gear GameObjects and configured them in your hierarchy. The gears are now part of a group under a central parent GameObject. You named your parent GameObject: “GearsMechanism.”

Here’s how you can use Transform.GetChild() to interact with one of the gears:

using UnityEngine;

public class GearController : MonoBehaviour
{
  public int gearIndexToRotate = 2; // Index of the gear to rotate (zero-based)
  
  private void Start()
  {
    Transform gearsMechanism = transform; // The parent GameObject holding all gears
    
    // Ensure the specified index is valid
    
    if (gearIndexToRotate >= 0 && gearIndexToRotate < gearsMechanism.childCount)
    {
      Transform selectedGear = gearsMechanism.GetChild(gearIndexToRotate);
      
      // Now you can manipulate the selected gear
      // For instance, make it rotate in the opposite direction
      selectedGear.Rotate(0f, 0f, -45f); // Rotate by -45 degrees around the z-axis
    }
    else
    {
      Debug.LogWarning("Invalid gear index specified.");
    }
  }
}

Here’s how to use this script:

  1. Add the GearController script to the GearMechanism GameObject.
  2. Set the gearIndexToRotate in the Inspector.
  3. Enter play mode.
  4. Observe how the gear that corresponds to the gearIndexToRotate has rotated.

Pretty cool, right?

📄 Inheritance Property in Practice:

  • When you rotate Gear0, Gear00 and Gear01 also rotate due to the inheritance property.

Iterating Through Children

When you want to get the children of a Transform, you use a foreach loop to iterate through the transform. During the foreach loop, you can perform an action on each child. For example, you could get the child’s name or scale. Then you can use that information in the parent component.

.GetChild() only returns a single child at a time. You can use it in a for loop to get each child.

The Foreach approach also returns a single child at a time. But, you get them as part of a for loop directly. This makes it easier to modify all the children.

Here’s how you use foreach:

foreach (Transform child in parent)
{
  Debug.Log(child.name);
}

Foreach does not recurse through nested children. If your child has another child, we call that a grandchild. The foreach loop does not include grandchildren or great-grandchildren.

Let’s consider an example. For this example, let’s say that you want to create a simulation of a virtual garden. In this simulation, you have a central garden bed. This is a GameObject named ""GardenBed"". The GardenBed contains various types of plants as its children. Each plant is a separate GameObject representing a different species.

You want the GardenBed to iterate through each plant in the garden. For each plant, you want the GardenBed to simulate the growth of the plant over time. To achieve this, create a script named PlantGrowthManager. Then, attach it to the GardenBed GameObject.

using UnityEngine;

public class PlantGrowthManager : MonoBehaviour

{
  [SerializeField]
  private float growthRate = 0.1f; // Rate of growth for the plants
  void Update()
  {
    Transform gardenBed = transform; // The Transform of the GardenBed GameObject
    
    // Iterate through all plants in the garden bed
    foreach (Transform plant in gardenBed)
    {
      
      // Simulate plant growth by increasing its scale over time
      Vector3 newScale = plant.localScale + Vector3.one \* growthRate \* Time.deltaTime;
      plant.localScale = newScale;
      
      // Check if the plant has reached its mature size
      if (newScale.x >= 5f)
      {
        Debug.Log(plant.name + " has reached mature size!");
      }
    }
  }
}

And there you have it. Now you have a base for your own garden simulation game!

As a quick recap, let’s go through the script again:

In this example, the PlantGrowthManager script gets the children of the GardenBed GameObject. It uses the foreach method to iterate through each plant. It simulates the growth of each plant by increasing the scale of the plant over time. When a plant is big enough, it logs a message. So, this is a rudimentary starter script for growing your plant garden.

In this example, the plant continues to grow even after it is mature. Try changing the script so that the plant stops growing once it is mature.

The plants also all grow at the same rate. Try changing the script so that each plant grows at a different rate.

Conclusion

Whether you are already familiar with how to use Transforms in Unity or starting out, this guide on how to get the children of a transform has you covered. Jump-start your Unity game development with my best practices and real-world examples.

Remember: What works in one project may not work in another project. Developing a great game in Unity is all about designing for the system architecture that is best for your project.

It all starts with understanding how to use Unity. Then, you can identify the right approach for your project. With the right approach, you can build your game to make your players happy.

This guide has everything you need to know to get started with manipulating and interacting with the children of a transform. Now it’s time to put those skills into practice.

Free download: Indie Game Marketing Checklist

Download now

Category

programming

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free