Coding with components
Components
in Unity are the building blocks of any game; almost everything you will use or apply will end up as a Component
on a GameObject
in a scene. When a GameObject
is selected, you can view each of its Components
from its Inspector.
You will find that you need to access these various components with script. Next we will discuss the various ways on which you can do this.
Accessing components
To reference the components of a GameObject from within your code, you need to use the GetComponent
function. The following shows you examples of how this is achieved:
Rigidbody myScriptRigidBody; void Awake() { var renderer = this.GetComponent<Renderer>(); var collider = renderer.GetComponent<Collider>(); myScriptRigidBody = collider.GetComponent<Rigidbody>(); ...
Get Mastering Unity 2D Game Development - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.