Game Development Reference
In-Depth Information
Figure 17.12 Scene-ClosingFail.
Global Variables
We've created all sorts of variables at this point. We've created public variables
(var nameOfVariable) that create a variable that can be populated within
Unity's editor. We've created private variables (private var nameOfVariable)
that store data, but usually are controlled and populated within the script.
We've created local variables whose scope is limited to just a particular
function.
The last type of variable we're going to cover is called a global variable .
Global variables actually do just what the name implies—they are variables
that are accessible globally. Importantly, a global variable remains constant
between scenes. This becomes ideal for something like health.
Step 44: Open the script HealthEngineScript.
Step 45: Convert the variable “health” from a private to global variable
and give it an initial value. Because we're defining an initial value in the
declaration, remove the line health = 100; from the Start function:
static var health : int = 100;
private var healthLevel : GameObject;
function Awake (){
healthLevel = GameObject.Find(“HealthLevel”);
}
function Start(){
healthLevel.guiText.text = health.ToString();
}
function ApplyDamage (damage : int){
health -= damage;
healthLevel.guiText.text = health.ToString();
if (health <=0){
KillPlayer ();
Search WWH ::




Custom Search