Game Development Reference
In-Depth Information
In the Project panel Assets ➤ Scripts folder, create a new script and name it CollisionColors.
Double-click its icon to open it for editing. Delete the Start() and Update() functions, then add the
following lines of code:
private var red : float;
private var green : float;
private var blue : float;
private var color : Color;
function OnCollisionEnter() {
Debug.Log("OnCollisionEnter");
color = GetRandomColor();
gameObject.renderer.material.color = color;
}
function OnCollisionStay() {
Debug.Log("OnCollisionStay");
}
function OnCollisionExit() {
Debug.Log("OnCollisionExit");
color = GetRandomColor();
gameObject.renderer.material.color = color;
}
function RandomColorValue() {
var randomValue : float;
randomValue = Random.Range(0.000, 1.000);
return randomValue;
}
function GetRandomColor() {
red = RandomColorValue();
green = RandomColorValue();
blue = RandomColorValue();
color = Color(red, green, blue);
return color;
}
Save the script, and return to the editor. Drag the script and drop it on the Sphere to attach it, then
save the scene. Play, and you'll see the sphere falls to the cube, changes color, and rolls across
the slanted top surface of the cube and over the edge, again changing color when it does. In the
Console, you'll find one "OnCollisionEnter" , multiple lines of "OnCollisionStay" , and finally one
"OnCollisionExit" .
Breaking this down, the color-changing code is familiar to you from Chapter 4. You declare float
values to hold the individual color values and a Color type reference variable to hold a randomly
generated Color's RGB values. GetRandomColor() calls RandomColorValue() to generate random
values for each of the Color RGB values, then assigns them to the color variable.
Search WWH ::




Custom Search