Game Development Reference
In-Depth Information
In the Start function, identify the GUI Texture component and set the starting
battery value:
5.
batteryRemaining = batteryFull; // full charge
guiTxt = GetComponent<GUIText>(); // the GUI Text object
guiTxt.text = "100%"; // full charge- assigned
In the Update function, add the timer:
6.
if(trackingBattery) {
if (batteryRemaining > 0){
batteryRemaining -= Time.deltaTime; // second countdown
percentRemaining = (int)((batteryRemaining / batteryFull) * 100); // round off for
percent
guiTxt.text = percentRemaining.ToString() + "%";
}
}
This timer counts downward. The variable, batteryRemaining , is the updated time left. Subtracting
Time.deltaTime subtracts a second at a time, but the time is divided over a second's worth of
frames. The current value is sent to the GUI Text component. Because batteryRemaining is a float,
it is converted or cast to an integer, using (int) , before it is converted to a string to update the text
value in the component.
7.
Save the script.
8.
Put it on the Battery Life object.
9.
Click Play, and watch it count down.
When the battery runs out, the Gnomatic Garden Defender must be disabled. It should neither be
able to move nor shoot. Let's disable the weapon first. Now you can switch the flag on from the
BatteryHealth script.
1.
Open the BatteryHealth script.
Below the if (batteryRemaining > 0) clause, add an else :
2.
else {
GameOver(); // it has run out
trackingBattery = false; // turn off battery timer
}
And create the GameOver function:
3.
void GameOver(){
// deactive the potato gun firing
GameObject.Find("Fire Point").SetActive(false);
}
4.
Save the script.
5.
Click Play, and try to fire potatoes after the battery has run out.
Search WWH ::




Custom Search