Game Development Reference
In-Depth Information
This new code breaking down as follows:
(1) waitTime -= Time.deltaTime;
Every time the Update() function is called, the time since the previous frame rendering is subtracted
from waitTime .
(2) if (waitTime < 0.0f) {
Check to see if the waitTime has counted down to zero.
(3) gameObject.renderer.material.color = Color.blue;
If the waitTime has elapsed, change the sphere material color to blue. If the waitTime has not
elapsed, the code between the brackets is not executed and the current material color remains
unchanged for this frame.
Save and play. Wait for it and . . . yes! After five seconds the sphere turns from a random color to blue.
Since you declared waitTime as a public variable, you can find it in the Inspector as part of the script
component. Any changes made here in the Inspector will override the initial scripted waitTime of 5.
User Input
That was a little more interesting, but entering and exiting Play mode is getting tedious. Add some
player interaction so when the N key (for New color) is pressed, a random color is generated for
the sphere's material. You don't know when the player might press the N key, so use the Update()
function to check for this with every frame. Edit the Update() function to add the following lines of
code at the end:
function Update()
{
waitTime -= Time.deltaTime;
if (waitTime < 0.0f) {
gameObject.renderer.material.color = Color.blue;
}
if(Input.GetKey(KeyCode.N)) {
red = RandomColorValue();
green = RandomColorValue();
blue = RandomColorValue();
alpha = RandomColorValue();
gameObject.renderer.material.color = Color(red, green, blue, alpha);
waitTime = 5;
}
}
 
Search WWH ::




Custom Search