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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With