Game Development Reference
In-Depth Information
In the Start() function, add the following line of code to the end of the function:
sphereCollider = GetComponent(Collider);
GetComponent(Collider) gets the reference to the sphere's collider component and assigns it to the
sphereCollider variable. In later chapters you will use GetComponent() to access the components,
including scripts, of other game objects.
+' on GetComponent() and you will be presented with a short list of options (Figure 4-16 ). Select
the first one: Component.GetComponent. Near the end of the reference you'll find one of Unity's
tips on optimizing performance. In this case, Unity is helpfully recommending that when possible,
use GetComponent with a type rather than a string. In our example we are using a type: our
sphereCollider variable of type Collider, rather than a string variable holding the name or tag of a
game object or component.
Figure 4-16. Scripting Reference +Scripting Reference lider, r GetComponent
Now add this conditional statement to the end of the Update() function:
if(Input.GetKey(KeyCode.C)) {
sphereCollider.enabled = !sphereCollider.enabled;
}
This conditional checks to see if the player has pressed the C key. If this is the case, then the collider
enable flag, a boolean value, is switched to its opposite. Look at this line of code closely:
(1) (2)
sphereCollider.enabled = !sphereCollider.enabled;
In Chapter 2 you learned that “ ! ” represents the logical operator NOT.
The boolean value of sphereCollider.enabled is either true or false .
Whichever value it is,
1.
2.
The NOT-value, or opposite value, is reassigned to the
sphereCollider.enabled flag.
 
Search WWH ::




Custom Search