Game Development Reference
In-Depth Information
Listing 4.8 Code to Test the Color of a Game Object Against
a Variable Value
var colorMatch:Material;
var score: int = 0;
function OnTriggerEnter (obj : Collider)
{
if(obj.gameObject.renderer.material.color ==
colorMatch.color)
{
score = score + 1;
}
}
Step 8. Attach countBalls.js to each of the spheres in the tops
of the beakers.
Step 9. For each sphere, select it in the Hierarchy and set the value of
Color Match by dragging the corresponding material from the Project
onto the script component.
Step 10. Because the code is attached to each sphere, each sphere
will keep a tally of the correctly colored balls. These four values
need to be added together to determine the total score. Open the
score.js script in the script editor and modify the existing code to
that in Listing 4.9 . The GetComponent() function gains access to the
countBalls script, which is attached to the sphere objects and pulls
out the score by referring to the variable by name.
Listing 4.9 Totalling a Score from Multiple Sub-Scores
var score = 0;
var scoreStyle: GUIStyle;
//create an array to hold all scoring objects
var scoringObjects: GameObject[];
function OnGUI ()
{
//reset the score value being displayed on the screen
score = 0;
//loop through each score object
for(var i = 0; i < scoringObjects.length; i++)
{
//extract the score from the object and tally
score + =
scoringObjects[i].GetComponent("countBalls").score;
}
GUI.BeginGroup (Rect (Screen.width − 85, 5, 80, 80));
Search Nedrilad ::




Custom Search