Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find children of children of a gameObject

Tags:

c#

unity3d

I have a prefab in scene and I want to access a child of that prefab, Structure of that prefab is like this:

PauseMenu
    UI_Resume
        TextField
        TextField2
            UI_Side_Back  <---- (I need this child)
    UI_Home

transform.FindChild return just first level child and loop in that transform is loop in first level child too:

foreach (Transform item in PooledPause.transform) {
        Debug.Log(item.name);
}

I think it's need to be a recursive method or something. How can I find that child?

like image 294
Hossein Rashno Avatar asked Oct 30 '15 13:10

Hossein Rashno


2 Answers

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;
    }
}
like image 62
Noel Widmer Avatar answered Oct 27 '22 19:10

Noel Widmer


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.

like image 23
Dan Puzey Avatar answered Oct 27 '22 19:10

Dan Puzey