Title says it all: What is the best way to find out how many children a gameObject
has via script.

- 121,791
- 22
- 236
- 328

- 123
- 1
- 2
- 8
-
1You might want to provide some code. What have you tried so far and what is the problem you're encountering? – Dec 06 '16 at 11:00
-
`foreach (Transform child in transform)` ? – mrogal.ski Dec 06 '16 at 11:01
2 Answers
EDIT 1:
A simple variable transform.hierarchyCount
, has been added to Unity 5.4 and above. This should simplify this.
OLD answer for Unity 5.3 and Below:
transform.childCount
provided by Adrea is usually the way to do this but it does not return a child under the child. It only returns a child that is directly under the GameObject transform.childCount
is been called on. That's it.
To return all the child GameObjects, whether under the child of another child which is under another child then you have to do some more work.
The function below can count child:
public int getChildren(GameObject obj)
{
int count = 0;
for (int i = 0; i < obj.transform.childCount; i++)
{
count++;
counter(obj.transform.GetChild(i).gameObject, ref count);
}
return count;
}
private void counter(GameObject currentObj, ref int count)
{
for (int i = 0; i < currentObj.transform.childCount; i++)
{
count++;
counter(currentObj.transform.GetChild(i).gameObject, ref count);
}
}
Let's say below is what your hierarchy looks like:
With a simple test script:
void Start()
{
Debug.Log("Child Count: " + transform.childCount);
int childs = getChildren(gameObject);
Debug.Log("Child Count Custom: " + childs);
}
This is the result between transform.childCount
and the custom function:
Child Count: 2
Child Count Custom: 9
As, you can see the transform.childCount
will not count childs of child but only child of the transform. The custom function was able to count all the child GameObjects.

- 1
- 1

- 121,791
- 22
- 236
- 328
-
-
@Andrea Nice. I really can't tell if OP wants to check for the first level or all the child but I do believe that Unity needs to clarify this in their doc. – Programmer Dec 06 '16 at 11:55
-
A part of what others have commented, it's important to note that `hierarchyCount` has a fixed value all the time, while `childCount` actually counts only the current children. In case your GameObject is dynamic (new elements apear or are destroyed), the former will always return the same value, while `childCount` will change. – Ivan Jan 31 '22 at 18:29
You can access its Transform and use transform.childCount.
Update: this method works for retrieving all children at the first level. If you want to retrieve the children in the overall hierarchy (also at the deeper levels), follow Programmer's answer.

- 6,032
- 2
- 28
- 55