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.
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>(); } void Update() { myScriptRigidBody.angularDrag = 0.2f * Time.deltaTime; }
This way, the Rigidbody
object that we want to affect can simply be discovered once (when the scripts awakes...