Game Development Reference
In-Depth Information
Underneath the Update() function, add the NewColor() function:
function NewColor() {
red = RandomColorValue();
green = RandomColorValue();
blue = RandomColorValue();
alpha = RandomColorValue();
gameObject.renderer.material.color = Color(red, green, blue, alpha);
waitTime = 5;
}
Now instead of using this code block twice, you can replace it in the Start() and Update() functions
with a call to NewColor() :
function Start()
{
// On Start, set a random color for the sphere material.
NewColor();
// Print the random color values to the Console.
print(gameObject.renderer.material.color);
}
function Update()
{
waitTime -= Time.deltaTime;
if (waitTime < 0.0f) {
gameObject.renderer.material.color = Color.blue;
}
if(Input.GetKey(KeyCode.N)) {
NewColor();
}
}
Your Start() function is cleaner and easier to read and so is your Update() function. If you find you
would like to change the sphere color during some other process you add in the future, you can do it
with the single line of code, NewColor(); .
Cleaning up your code by rewriting portions of it is known as refactoring . Refactoring as a project
progresses in order to keep the scripts clean and simple is an excellent habit to develop and
ultimately makes life easier for you.
 
Search WWH ::




Custom Search