user285372
user285372

Reputation:

Active game object not being found

As can be seen in the attached image, I have an active game object with a few children, but the following simple strategy returns null, suggesting that it cannot be found or reached.

What am I doing wrong? I just need to grab this joint and make some modifications to it...

void Start()
{
    GameObject brad = GameObject.Find("Brad");
    GameObject hip = brad.transform.Find("Brad/ChrBrad/CharacterRoot/JtRoot/JtPelvis").gameObject;
}

At first, I only used GameObject hip = brad.transform.Find("JtPelvis").gameObject; so I thought that might be the problem, but even after specifying the full path, it is still unfindable?!

enter image description here

Upvotes: 2

Views: 61

Answers (1)

Yuri Nudelman
Yuri Nudelman

Reputation: 2943

1) Transform.Find (not to be confused with GameObject.Find) searches only one level down (not in grandchildren), this is why brad.transform.Find("JtPelvis").gameObject did not work;

2) You can find "JtPelvis" by full path, just omit the "Brad":

GameObject hip = brad.transform.Find("ChrBrad/CharacterRoot/JtRoot/JtPelvis").gameObject;

3) Alternatively, you can always write some custom search function, for example:

Transform FindChildNamed(Transform t, string name) {
    if (t.name == name) return t;
    foreach (Transform t1 in t) {
        return FindChildNamed(t1, name);
    }
    return null;
}
//....
GameObject hip = FindChildNamed(brad.transform, "JtPelvis").gameObject;

Upvotes: 2

Related Questions