Game Development Reference
In-Depth Information
04 public class MyScriptFile : MonoBehaviour
05 {
06 public string PlayerName = "";
07 public int PlayerHealth = 100;
08 public Vector3 Position = Vector3.zero;
09
10 // Use this for initialization
11 void Start () {
12 }
13
14 // Update is called once per frame
15 void Update ()
16 {
17 //Check player health - the braces symbol {} are option
for one-line if-statements
18 if(PlayerHealth == 100)
19 {
20 Debug.Log ("Player has full health");
21 }
22 }
23 }
The preceding code is executed like all other types of code in Unity, by pressing the
Play button from the toolbar, as long as the script file has previously been instantiated
on an object in the active scene. The if statement at line 18 continually checks the
PlayerHealth class variable for its current value. If the PlayerHealth variable is
exactly equal to ( == ) 100 , then the code inside the {} braces (in lines 19-21) will be
executed. This works because all conditional checks result in a Boolean value of either
true or false ; the conditional statement is really checked to see whether the queried
condition ( PlayerHealth == 100 ) is true . The code inside the braces can, in theory,
span across multiple lines and expressions. However, here, there is just a single line
in line 20: the Debug.Log Unity function outputs the Player has full health string to
the console, as shown in the following screenshot. Of course, the if statement could
potentially have gone the other way, that is, if PlayerHealth was not equal to 100
(perhaps, it was 99 or 101 ), then no message would be printed. Its execution always
depends on the previous if statement evaluating to true .
 
Search WWH ::




Custom Search