Game Development Reference
In-Depth Information
A better way to use components - referencing
Now, every programmer knows that they have to worry about garbage and exactly how
much memory they should allocate to objects for the entire lifetime of the game.
To improve things based on the preceding shortcut code, we simply need to manually
maintain the references to the components we want to change or affect on a particular ob-
ject. So, instead of the preceding code, we could simply use the following code:
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); then, we can just update the reference each time a value needs
to be changed instead of discovering it every time.
Search WWH ::




Custom Search