Find children of children of a gameObject

Here is yet another solution that let's you find children in any depth based on any criteria. It uses a depth-first approach. I therefore recommend to place objects of interest as high up the tree as possible to save some operations.

It is used like this: parent.FindRecursive("child");

Or if you need more flexibility: parent.FindRecursive(child => child.GetComponent<SpriteRenderer>() != null && child.name.Contains("!"));

using System;
using UnityEngine;

public static class TransformExtensions
{
    public static Transform FindRecursive(this Transform self, string exactName) => self.FindRecursive(child => child.name == exactName);

    public static Transform FindRecursive(this Transform self, Func<Transform, bool> selector)
    {
        foreach (Transform child in self)
        {
            if (selector(child))
            {
                return child;
            }

            var finding = child.FindRecursive(selector);

            if (finding != null)
            {
                return finding;
            }
        }

        return null;
    }
}

You can use a path to find a transform:

 var target = transform.Find("UI_Resume/TextField2/UI_Side_Back");

From the documentation for Transform.Find:

If name contains a '/' character it will traverse the hierarchy like a path name.


The "RecursiveChildFind" above does not work, as it will only search one child, not all of them. A working version is below:

Transform RecursiveFindChild(Transform parent, string childName)
{
    foreach (Transform child in parent)
    {
        if(child.name == childName)
        {
            return child;
        }
        else
        {
            Transform found = RecursiveFindChild(child, childName);
            if (found != null)
            {
                    return found;
            }
        }
    }
    return null;
}

I tried all the solution but none worked for me. Using the Unity Find not worked because I don't know the name of the parent of my child. The recursive solution here only work if you have parent with only one child, what isn't my case too. So, I create the following generic recursive finder that work in any type of GameObject hierarch (or tree).

public static Transform RecursiveFindChild(Transform parent, string childName)
{
    Transform child = null;
    for (int i = 0; i < parent.childCount; i++)
    {
        child = parent.GetChild(i);
        if (child.name == childName)
        {
            break;
        }
        else
        {
            child = RecursiveFindChild(child, childName);
            if (child != null)
            {
                break;
            }
        }
    }

    return child;
}

Note: use that carefully, avoid big GameObject trees.

Tags:

C#

Unity3D