Home > database >  Unity use Transform Find the name as same as parent name return null in unity player
Unity use Transform Find the name as same as parent name return null in unity player

Time:06-19

In my Hierarchy, I have a gameobject like this GameObject/GameObject, the parent and child nodes have the same name. i want get the child gameobject, i used the flowing code:

 GameObject parent = GameObject.Find("GameObject");
 Transform childTransform = parent.transform.Find("GameObject");

this code work well in unity Editor, but when i build it out, the childTransform is null, why? I'm confused about it.

Does anyone know why

CodePudding user response:

GameObject.Find does not guarantee anything about the search traversal order. Thus in build, it might search differently, for reasons that are not exposed to users.

GameObject.Find, however, does support path-like names, so you access the child like this:

GameObject.Find("path/to/parent/GameObject/GameObject")

If that is not enough, you will have to resort to a manual traversal of the hierarchy.

CodePudding user response:

You just don't need to find all the objects with GameObject.Find, use GetChild.

var parent = GameObject.Find("GameObject");

if (parent.transform.childCount > 0)
{
    var childTransform = parent.transform.GetChild(0);
    
    Debug.Log(childTransform); // child name..
}
  • Related