Game Development Reference
In-Depth Information
Say you also would like to give the user the option of changing the sphere color with the click of the
mouse. Add the following function to your script underneath NewColor() :
function OnMouseDown() {
NewColor();
}
Isn't that much nicer than duplicating six lines of code again? Save and play.
If you didn't read the OnMouseDown() scripting reference first, you might be surprised to find that
clicking with the mouse just anywhere in the Game view doesn't cause a color change, you must
click directly on the sphere.
+' OnMouseDown() and you'll find in the Scripting Reference description that this function is only
called when the mouse button is clicked while the mouse cursor is hovering over the GameObject
collider.
Select the sphere in the Hierarchy or Scene view and you'll see that in the Inspector that just as
when you used Unity's cube primitive game object, Unity created the sphere primitive game object
with the necessary collider component required for it to work as advertised with the OnMouseDown()
function.
Enabling and Disabling Components
In addition to manipulating the properties of components to engender the desired behavior, you
can also enable and disable entire components. OnMouseDown() requires interaction with a collider
component. You just proved that it works with a collider component, now test to see if it fails to work
when the collider component is disabled.
An easy way to prove this is to simply uncheck the box in the Inspector panel for the sphere's
Sphere Collider to disable it. This checkbox represents a boolean flag , where if the box is checked
then the enabled flag is set to true , and if the box is unchecked then the enabled flag is set to false .
Go ahead and uncheck the box, then enter play mode to test. As expected, if you try clicking on the
sphere with the mouse while the collider component is disabled, nothing happens. Exit Play mode
and check the box to enable the collider component again. While this is an easy way to test the
concept, enabling or disabling a component during gameplay takes place in a script.
Add a new variable declaration to the list after #pragma strict :
private var sphereCollider : Collider;
This variable declaration is a little different than the ones you've made before in that its type is
Collider. The sphereCollider variable is necessary for accessing the enable property of the collider
component from within the script. Unlike a float or int variable that holds a specific numerical value,
sphereCollider is a reference variable . It holds a reference to the memory address where the data
that defines the Collider is held, not the data itself.
 
Search WWH ::




Custom Search