Getting all GameObjects in hierarchy with certain name

Hi,

I am looking for a clever way to get all game objects with a certain name in a hierarchy.

example)

-BodyGO

    • ArmGO
      • MountPointGO

-BodyGO

    • ArmGO
      • MountPointGO

If I have 2 instances (or more realisticly hundreds) of BodyGO. I want to find only the MountPointGO in my BodyGO hierarchy.

I could do GameObject.Find(“MountPointGO”) but that is not guaranteed to give me the one in my hierarchy.

I could also do GameObject.GetGameObjectsWithTag and Tag my MountPointGOs, then go through the list and find which one is in my hierarchy through Transform.IsChildOf, but that seems like too much work for what I want to do.

Assuming that my MountPointGO only has a transform on it, so that I couldn’t use GetComponentsInChildren on it effectively, is there a better way to do this?

You could do:

List<GameObject> objsWithSameName = new List<GameObject>();
foreach(Transform obj in myRootObject.transform)
{
    if(obj.name == myTargetNameString)
        objsWithSameName.Add(obj.gameObject);
         
}

You search the whole transform for children whose names match the search string, and store the ones that do on a list.

If your hierarchy goes deep, you could put that loop in a function, and recursively call it for each gameobject you go through…

In the end, you get a list of objs with the same name.

Hope this helps

Cheers

You could also use Transform.Find if you have the root objects (and the hierarchy matches)

Transform.Find will search only within children and is more precise.

If the hierarchy is:
Root
->Middle
–>Child

Then Root.transform.Find(“Middle/Child”); will get the proper Transform, but Root.transform.Find(“Child”) will return null.
It’s not so good for finding all Mount Points on a model, but if you store the paths to those mount points it is a much faster and safer method than GameObject.Find for finding sub objects.

Thanks HarveteR and Ntero for your suggestions.

I also found another way to do it is to make a simple MountPoint class where you could even specify some offsets if you like.
This way we could simply use Root.GetComponetsInChildren()

It turned out that for my example I just put the referring script in my MountPointGO, so I didn’t need to use any of these approaches and could access the transform directly.