Why do I always have to use GetComponent?

Hi guys, I’m not sure what has happened to my unity.

Before when I wanted to use the rigidbody component of an object, I could just type gameobject.rigidbody.etc (YES MY OBJ HAS A RIGIDBODY ATTACHED)

Now, when I do that, the option ‘rigidbody’ is gone, and unity says I’m using an obsolete API. Now I have to always type gameObject.GetComponent().etc… FOR EVERYTHING.

Can anyone tell me why this is happening? I’m watching tutorials and no1 else seems to have the same issue… it’s getting annoying lol

That’s a change made in Unity 5, for API design reasons.

You shouldn’t really be using GetComponent very frequently, anyway. Cache the result once in a variable and then call that.

1 Like

yawwwnn alright fair enough.

Thank you.

Well since you asked for a why.

The short cut accessors were built early in the days of Unity. As Unity has gotten bigger its attracted bigger and bigger games. And several engine problems have been highlighted. Some of the problems caused by the short cut accessors are:

  • Engine dependency
  • Inconsistent application
  • Slow performance
  • Methods that look like properties

All of these lead too

  • Performance problems
  • Large build sizes for WebGL
  • Slower engine updates

So the short cut accessors got nerfed in 5.0

5 Likes

Much appreciated, thank you.

ya just grab the rigidbidy in your start or awake, and save it to a member variable