[Solved] Get number of children a game object has via script


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:

enter image description here

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.

3

solved Get number of children a game object has via script