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 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.
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.