Game Development Reference
In-Depth Information
Debug.Log ("Player has full health");
}
The if-else statement
One variation of the
if
statement is the
if-else
statement. The
if
statement performs a code block if its condition evaluates to
true
.
However, the
if-else
statement extends this. It would perform
an
X
code block if its condition is
true
and a
Y
code block if its
condition is
false
:
if(MyCondition)
{
//X - perform my code if MyCondition is true
}
else
{
//Y - perform my code if MyCondition is false
}
The switch statement
As we've seen, the
if
statement is useful to determine whether a single and specific
condition is
true
or
false
and to perform a specific code block on the basis of this.
The
switch
statement, in contrast, lets you check a variable for multiple possible
conditions or states, and then lets you branch the program in one of many possible
directions, not just one or two as is the case with
if
statements. For example, if
you're creating an enemy character that can be in one of the many possible states of
action (
CHASE
,
FLEE
,
FIGHT
,
HIDE
, and so on), you'll probably need to branch your
code appropriately to handle each state specifically. The
break
keyword is used to
exit from a state returning to the end of the
switch
statement. The following code
sample 1-3 handles a sample enemy using enumerations:
01 using UnityEngine;
02 using System.Collections;
03
04 public class MyScriptFile : MonoBehaviour
05 {
06 //Define possible states for enemy using an enum
07 public enum EnemyState {CHASE, FLEE, FIGHT, HIDE};
08