Game Development Reference
In-Depth Information
Accessing components using a shortcut
Now, in the previous Unity example, we added some behind-the-scenes trickery to enable
you to reference a component without first discovering it. We did this by adding shortcuts
to the
MonoBehavior
class that the game object inherits from. You can access the com-
ponents with the help of the following code:
this.renderer.collider.attachedRigidbody.angularDrag = 0.2f;
Tip
Downloading the example code
You can download the example code files for all Packt topics you have purchased from
your account at
http://www.packtpub.com
.
If you purchased this topic elsewhere, you can
visit
http://www.packtpub.com/support
and register to have the files e-mailed directly to
you.
What Unity then does behind the scenes for you is that it converts the preceding code to
the following code:
var renderer = this.GetComponent<Renderer>();
var collider = renderer.GetComponent<Collider>();
var ridgedBody = collider.GetComponent<Rigidbody>();
ridgedBody.angularDrag = 0.2f;
The preceding code will also be the same as executing the following code:
GetComponent<Renderer>().GetComponent<Collider>().GetComponent<Rigidbody>().angularDrag
= 0.2f;
Now, while this is functional and working, it isn't very performant or even a best practice
as it creates variables and destroys them each time you use them; it also calls
GetCom-
ponent
for each component every time you access them. Using
GetComponent
in the
Start
or
Awake
methods isn't too bad as they are only called once when the script is
loaded; however, if you do this on every frame in the
update
method, or even worse, in
FixedUpdate
methods, the problem multiplies; not to say you can't, you just need to be
aware of the potential cost of doing so.