GetComponentsInChildren isn't returning all children, just the first level.

Hello! I was under the impression based on lots of forum posts that GetComponentsInChildren would return the object selected, all of it’s children, and all their children etc. This doesn’t seem to be happening as when I run the code below, I only get results from the immediate children.

Any thoughts?

static function ShowPolycount () {
    if (Selection.activeObject.GetType() == UnityEngine.GameObject)
    {
        var totalTriCount        : int        = 0;
        // Get count of parent object if applicable
        if (Selection.activeGameObject.GetComponent.<MeshFilter>())
        {
            var parentMesh         : Mesh     = Selection.activeGameObject.GetComponent.<MeshFilter>().sharedMesh;
            var parenttri        : int    = parentMesh.triangles.Length / 3;
            totalTriCount        += parenttri;
        }
        // Get count of all children of object
        var allChildren = Selection.activeGameObject.GetComponentsInChildren(Transform);
        for (var child : Transform in Selection.activeGameObject.transform) {
            print ("Object: " + child.name);
            if (child.gameObject.GetComponent.<MeshFilter>())
            {
                var objMesh         : Mesh     = child.gameObject.GetComponent.<MeshFilter>().sharedMesh;
                var triCount        : int    = objMesh.triangles.Length / 3;
                totalTriCount        += triCount;
            }
        }
        print ("There are " + totalTriCount + " triangles.");
    }
}

You have two entirely different methods one after the other:

var allChildren = Selection.activeGameObject.GetComponentsInChildren(Transform);

should return all children, recursively. That means children of children of children too. However, you don’t use this list at all, and instead:

for(var child : Transform in Selection.activeGameObject.transform)

which will only iterate over the objects that have the currently selected transform listed as “parent”, explicitly- ie: only the first layer of children. If you want to iterate over all of them, since you went through the trouble to get all of them already, iterate over “allChildren” instead.

Worth noting, in case you don’t know already, that this will return the transform of the selected object as well, and not just its children. If you want an operation performed only on the children, you’ll need to check the child Transforms against the selected GameObject’s Transform and skip that one.

1 Like

Thank you! Silly me :smile:

That line should read:

for (var child : Transform in allChildren) {