How to recursively count all child nodes in Unity?

In Unity, a recursive method can be used to count all child nodes. Here is an example code for counting the number of all child nodes:

using UnityEngine;

public class RecursiveCount : MonoBehaviour
{
    private int count = 0;

    private void Start()
    {
        CountChildren(transform);
        Debug.Log("Total Count: " + count);
    }

    private void CountChildren(Transform parent)
    {
        count += parent.childCount;

        foreach (Transform child in parent)
        {
            CountChildren(child);
        }
    }
}

The code above utilizes a private variable, count, to store the number of child nodes. In the Start method, the CountChildren method is called, passing in the transform of the current object. The CountChildren method first adds the childCount of the current object to count, then recursively traverses each child node, calling CountChildren again to count the number of child nodes for each child node.

Finally, output the value of count in the Start method, which is the total number of child nodes.

bannerAds