Unity: Get Child by Name
In Unity, beginner game developers frequently try to set up interactions between game objects by identifying these objects by name. Getting the object by name is a beginner-friendly approach that is straightforward for newcomers. So, this guide will explain how to find children by name.
However, I recommend against finding children by name.
Instead, you should use a Component to identify specific types of objects and then use GetComponentsInChildren to find things with that component. This approach is more reliable and robust. If you rename the child, the method still works. If you rename the component, the method still works.
Sometimes, you will want to get a child by name for quick prototyping or debugging. Fortunately, it is easy to do. In this guide, I'll explain how to do it.
How do I find a child by name?
Use Unity's Transform.Find method. As the parameter, pass in the exact name of the child you want to find.
Transform child = transform.Find(“childName”);
`Transform.Find()` only looks at the first level in the hierarchy. Sometimes, you want to find children in lower levels of the hierarchy. In the next section, I'll explain how.
How do I find a grandchild by name?
You have two options. Specify an exact path or iterate through the list of all children.
For example, assume your hierarchy looks like this:
Now imagine that you call transform.Find("Grandchild") from the Parent. This call will return null.
Method 1: Specify the exact child path
In this method, you can specify the exact child path. As you can see, we use a "folder-like" slash to distinguish each path. You can use this as many times as you want.
In this method, you become dependent on more than one name. The immediate child as well as the grandchild. Specifying the exact child path is error-prone - even more so than using transform.Find() alone. I recommend against this approach.
Method 2: Get all children, then match by name
The second method is more complex, but more robust. For that reason, I recommend it. In this approach, you get all children, then match them by name.
Transform transforms = GetComponentsInChildren<Transform>();
foreach (Transform t in transforms)
if (t.name == "Grandchild")
Learn more about how to get all children of a transform.
As you can see, getting a child by name in Unity is straightforward. To reinforce what I mentioned earlier, you should generally avoid this method. Instead, use components to identify GameObjects and filter with those components.
Continue brushing up your Unity skills with our Unity basics series:
65+ Tips: How to improve a Unity Game's Performance
65+ tips to help you improve your Unity game's performance.
The basics of arrays in C#. Declaring, initializing, assigning values, accessing elements, and using foreach loops.
Low Poly Trees
This article outlined the world of low poly trees. You learned how to make low poly trees. You also learned where to use low poly trees.