-3

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

Programmer
  • 121,791
  • 22
  • 236
  • 328
Peyton
  • 123
  • 1
  • 2
  • 8

2 Answers2

6

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.

Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Thank you for the clarification, +1. I edit my answer to specify that. – Andrea Dec 06 '16 at 11:50
  • @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
4

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.

Andrea
  • 6,032
  • 2
  • 28
  • 55