I’m having trouble understanding how GameObject.Find works and I was wondering if someone could help me.
Say I have the scene:
PlatformA
ObjectB
PlatformB
ObjectB
Then in my script somewhere I have PlatformA stored in a variable called “platform”. How do I find the ObjectB that is a child of the object stored in “platform”?
I was hoping I could do
var obj = platform.Find("ObjectB");
but apparently that searches the entire project and returns a random “ObjectB”.
If I’m reading the docs right, if I specify the full path to the object /PlatformA/ObjectB it will find the correct thing, but that requires me to travel up the transform.parent tree to find the names of all the objects. Is there any way to FindChild(“ObjectB”)?
You’re close, but you’re one degree off.
platform.transform.Find(“ObjectB”);
Now it’ll only search the children of object “platform” for ObjectB, not the entire project.
Keep in mind though that returns a transform. If you want the GameObject it’s
this.transform.Find(“ObjectB”).gameObject;
I like to use this for my prefabs if the object is down a few levels.
this.transform.root.Find(“ObjectB”).gameObject;
Personally, I just store references to anything I’ll be searching for regularly. I figure it’s got to speed things up at least a little.
D’oh, I was so close. Thanks!
I was wondering about the same question.
I spend quite a bit of time trying to look for the right method.
The described method is pretty convoluted/confusing trying to find the object.
API should be added/changed to better reflect more intuitiuve method.
And what’s the difference between transform.Find() and transform.FindChild()?
Does FindChild work anymore? It’s not in the documentation, the only reference I can find on the forum is from 2005. I imagine it’s now been replaced with transform.Find, as that searches the children.
There is no FindChild, I don’t think. Find() searches the children of the object on which it is executed.
There is FindChild(), although it’s not documented.
I still think there should be an API to find child object from GameObject instead off of Transform. The API seems little unintuitive.
For instance, you may want to have logical children for grouping purpose even if Transform doesn’t exist.