Search code examples
c#for-loopunity-game-enginechildren

Keeping track of the number of Children of a GameObject


I wrote this bit of code to count the children of a GameObject in my scene. It works but doesn't feel like the most elegant solution (particularly the line where I reset the childCount to 0 each time). Could someone offer me some re-write suggestions on this to make it more streamlined?

public int childCount;

public void countChildren() 
{
    GameObject buildBoard = GameObject.FindGameObjectWithTag("Board");

    GameObject[] allChildren = buildBoard.transform.Cast<Transform>().Select(t=>t.gameObject).ToArray();

    childCount = 0;

    for(int i = 0; i < allChildren.Length; i++)
    {
        childCount++;
    }

    Debug.Log(childCount);
}

Solution

  • I think you don't have to cast to Transform because GameObject.transform already returns Transform type. And Transform already has Transform.childCount method. So you can count like this:

    public int childCount;
    public void countChildren() 
    {
        GameObject buildBoard = GameObject.FindGameObjectWithTag("Board");
    
        childCount = buildBoard.transform.childCount;
    
        Debug.Log(childCount);
    }
    

    You can also wrap it into a little helper method:

    public int CountChildrenForObjectWithTag(string tag)
    {
        var gameObject = GameObject.FindGameObjectWithTag(tag);
    
        if (gameObject == null || gameObject.transform == null) return 0;
    
        return gameObject.transform.childCount;
    }