If I have a GameObject
with multiple Component
classes attached to it of the same type (let's call this type HingeJoint
for example purposes), which HingeJoint
component will I get if I called the function GetComponent<HingeJoint>()
on my GameObject
?
According to my research, this answer claims Unity will simply return the first match from the array of Component
s--however, the answer is only an educated guess based on the answerer's own game engine design that strives to mimic Unity and not an authoritative source for what Unity actually does.
Every object and it's subobjects in Unity are hierarchically placed in a collection. You can call it a "WYSIWYG" because as you see every object in the scene hierarchy is loaded in the same order they are displayed on that list. The same thing applies to the components and it's the main reason why Transform
component is placed on top of every other component.
GetComponent
will return the first item from the collection of Components
seen from the top of the list. To be exactly sure which component will be returned you can order them as you wish in the inspector view.
From the documentation page:
The order you give to components in the Inspector window is the order you need to use when querying components in your user scripts. If you query the components programmatically, you’ll get the order you see in the Inspector.