Find kids children gameObject

I have a prefab in the scene and I want to access the child of this collection. The structure of this collection is as follows:

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

transform.FindChildreturns only the parent of the first level and loopin that the transformation is also a loop in the child of the first level:

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

I think it should be a recursive method or something like that. How can I find this baby?

+6
source share
3 answers

You can use the path to find the transformation:

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

From the documentation forTransform.Find :

If the name contains the character "/", it will go through the hierarchy as the path name.

+10
source

Unity3D , . :

  public static T FindComponentInChildWithTag<T>(this GameObject parent, string tag)where T:Component{
       Transform t = parent.transform;
       foreach(Transform tr in t)
       {
              if(tr.tag == tag)
              {
                   return tr.GetComponent<T>();
              }
              else
              {
                   tr.GetComponent<T>().FindComponentInChildWithTag(tag);
              }
       }
  }

.

, - :

if(tr.name == "object name")

find() :

tr.Find("Bone");

//or

parent.Find("UI_Resume/TextField2/UI_Side_Back");
+1

Thanks Dan Puzeyfor the reply. Also, if you want to have a recursive loop for your object, you can implement this as follows:

void Start()
{
    GameObject theChild = RecursiveFindChild (theParentGameObject.transform, "The Child Name You Want");
}

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

    return null;
}
+1
source

Source: https://habr.com/ru/post/1613842/


All Articles