- Home /
The better (and the less expensive) way to find a GameObject?
Hello guys, I have a great perplexity, and I hope someone can give me some advice :)
In term of performance, what is the less ‘expensive' way in order to find a gameobject?
1) Public GameObject myGO;
2) GameObject myGO = this.transform.parent.GetChild(0).GetChild(0).gameObject;
3) GameObject myGO = GameObject.Find("myObject")
Thanks a lot! :)
Answer by tormentoarmagedoom · Feb 01, 2019 at 09:31 AM
Good day.
1- For performance, best option is to assign the object via inspector (public variable)
2- But this can be almost impossible for so many cases, then, 2nd best option is to find it via transform/childs from an object already known (this parent defined via inspector public variable) https://docs.unity3d.com/ScriptReference/Transform.Find.html
3- If you need to find it from "0", no other references, then best option is using https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
You can also find it (most used option i think) by finding all the objects with a speecific tag with a foreach loop to find all of them (you get an array) https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html and then use an if (name == something) or if (position) or something to select the exact object from that array
4- And last way (less performance, more CPU needed) is using https://docs.unity3d.com/ScriptReference/GameObject.Find.html
Bye!
Thanks a Lot @tormentoarmagedoom! Have a nice day! :)
Actually his second example would be in between your first and second point. Using GetChild is most likely faster than using Transform.Find. However unless you can guarantee the structure of your hierarchy i would always use Transform.Find if possible. $$anonymous$$eep in $$anonymous$$d that you can use a "path" structure in a single Transform.Find call:
GameObject myGO = transform.parent.Find("Child1/NestedChild").gameObject;
This works as long as the names of the gameobjects don't change. Relying on the child order is never a good idea. Also keep in $$anonymous$$d to cache such references. So you wouldn't / shouldn't execute this very often, so the performance becomes quite irrelevant. It's more important to have robust code that doesn't break when you add another child to one of those objects.
Your answer
![](https://koobas.hobune.stream/wayback/20220612190901im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C# Invoke vs. Unity SendMessage 2 Answers
Does a coroutine do all its work during one frame? 1 Answer
Problem with Unity 4 and Nvidia GTX 600 series video cards 0 Answers
character view range 2 Answers
Profiler Windows - What is "Others" 1 Answer