Search code examples
c#unity-game-enginegame-enginegameobject

Unity GetComponent<Type> 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 Collider2Ds and want to know which one would be returned and if it's consistent.


Solution

  • If more than one Component is attached that matches the specified Type, Unity will return the first one. However, do not rely on this, as which one is "first" may not be under your control. It will be deterministic, but may change unexpectedly due to how Unity maintains, serializes, and stores the data internally.

    This is why it's generally not recommended that you have more than one of the same type of component (e.g. colliders) attached to the same game object. If you need more than one, use children.