- Home /
Find children in parent
Hello all , So this is my question . I have a game object that contains 4 children . I want it to get one of those children (can search it by name) ? how do I do this through code? Thanks a lot in advance.
Answer by UnityLib43 · May 20, 2017 at 01:27 PM
Try this: gameobject.transform.Find("ChildName") ; on the parent gameobject
Does it only loop in the paren'ts children or in all of the gameobjects in the scene ?
Answer by CapeGuyBen · May 20, 2017 at 01:07 PM
In Unity, the hierarchy information is stored in the Transform component rather than the GameObject itself. You can find a child with a given name using the Find method on the Transform:
GameObject GetChildWithName(GameObject obj, string name) {
Transform trans = obj.transform;
Transform childTrans = trans. Find(name);
if (childTrans != null) {
return childTrans.gameObject;
} else {
return null;
}
}
Thank you for your answer . Does your solution only loop in the paren'ts children or in all of the gameobjects in the scene ?
Even better :
public static GameObject GetChildWithName<T>(this T obj, string name) where T : Component
{
Transform trans = obj.transform;
Transform childTrans = trans.Find(name);
if (childTrans != null)
{
return childTrans.gameObject;
}
return null;
}
Edit : If you need deep (more than 1 children down) : https://answers.unity.com/questions/799429/transformfindstring-no-longer-finds-grandchild.html
Answer by Artaani · May 20, 2017 at 01:08 PM
Place this code on parent object:
foreach (Transform eachChild in transform) {
if (eachChild.name == "NameWhatYouNeed") {
Debug.Log ("Child found. Mame: " + eachChild.name);
}
}
Update: Method above is better. Didn't know that.
Answer by nitinDhami · May 20, 2017 at 01:27 PM
you can use tranform.getchild(index) to get any one of them
Answer by metixgosu · May 10, 2021 at 06:59 AM
It is Transform not transform. https://docs.unity3d.com/ScriptReference/Transform.html