Instructor mentioned that finding a game object with the player controller or finding a game object with the name “player” were expensive. I assume he meant for performance but wanted to ask for some explanation.
Yes, he means in performance. One, however, is less expensive than the other.
So here’s what happens when you perform a FindObjectOfType<T>()
The method looks at every GameObject in the game and all of it’s children, then on each object, it looks through it’s component until it finds a component of type <T>
. (T stands for whatever type you put in the method). This is very expensive, and is not something you should ever do within an Update() loop. The good news is that the Singular version of the script stops when it finds the first instance of the component. FindObjectsOfType<T>()
returns an T[]
containing every instance of T, meaning that no short circuit, every GameObject and every component is checked.
Now FindWithTag(string) is a bit better than FindObjectOfType, because it only looks at the GameObjects within the scene and compares their tags to the provided string. It doesn’t have to check each component, which saves some time.
This is better than FindObjectOfType, but still not ideal for Updates.
I’m not saying you shouldn’t use either of these methods, far from it. There are times when you need them. It’s best to use them in Awake(), so they become part of the loading process and will go unnoticed. Then you can cache the result, and not bog down an Update loop.
Awesome. Thanks for the detailed answer. Very Helpful
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.