Game Development Reference
In-Depth Information
11 {
12 //Get cached reference to transform
13 ThisTransform = GetComponent<Transform>();
14 }
15 //-----------------------------------------------------
16 // Update is called once per frame
17 void Update ()
18 {
19 //Update position
20 if(ThisTransform !=null) {ThisTransform.localPosition +=
Time.deltaTime * 10.0f * ThisTransform.forward;}
21 }
22 //-----------------------------------------------------
23 }
24 //-----------------------------------------------------
The following are the comments on the code sample 3-1:
Lines 07 and 13 : The variable ThisTransform is declared as private.
This variable is assigned a reference to the Transform component attached
to the GameObject , and it achieves this inside the Start event using the
GetComponent function. In the case of accessing the Transform component
specifically, we could also have used an inherited transform property,
such as ThisTransform= transform; .
Line 20 : Here, the ThisTransform variable is used directly to set the
localPosition of the GameObject . Again, for the Transform component
specifically, we could also have used transform.localPosition .
However, this approach internally invokes an extra function call, because
the member transform is a C# property and not a standard variable. More
on properties can be found in Chapter 1 , Unity C# Refresher . For this reason,
using GetComponent inside a Start or Awake event to retrieve a component
reference to a private class variable is typically one of the most efficient ways
to access external components, especially if the component must be accessed
regularly, such as inside an Update function.
 
Search WWH ::




Custom Search