- Home /
Unity GetComponent return value
Which game object of type Type
is returned from the call
GetComponent<Type>();
if the calling game object has more than one object of that type attached?
The documentation for this function only says a game object is returned if it exists, else null.
I have a game object with multiple Collider2D
s and want to know which one would be returned and if it's consistent.
Answer by kalen_08 · Jul 26, 2018 at 09:29 PM
The first one in order from top to bottom in the inspector is the order in which they are returned I believe. If you do GetComponent then the top most component of that type is returned. If you have a circle collider and box collider and or other different more specific types then do
GetComponent<BoxCollider2D> ()
Right. In the past Unity didn't have a particular order. It just returned the first in its internal list of components on that gameobject. However since i think Unity 5.x the component order is now preserved. Actually they new audio filters rely on the order of the components. Since then we now have even the option to change the order of components in the inspector.
It works the same way for
FindGameObjectWithTag("tag")
FindGameObjectOfType...
etc