Conditional Statements

Conditional Statements

Conditional statements are how we get the computer to check for a condition and take action.

Here is how you write a conditional statement:

if(condition)
{
commands to do if condition is true
}

Example: if Statement

if(health > 0)          //The condition is health > 0.  if true the Debug command will run
{                                //If the condition is false it will skip the command
Debug.Log(“Player is alive!”);        //Debug.Log sends info to the console
}

If you want to run a command if the condition is false, then you would use an else

Example: if statement with an else

if(health > 0)          //The condition is health > 0.  if true the Debug command will run
{                                //If the condition is false it will skip the command
Debug.Log(“Player is alive!”);
}
else        //else will run it’s command if the condition in the if statement is false
{
Debug.Log(“Player is dead”);
}

You can also check a second condition with an else if statement.

Example:  else if statement

if(health < 25)          //The condition is health < 25.  if true the Debug will run
{                                //If the condition is false it will skip the command
Debug.Log(“Player’s health is low!”);
}
else if(health > 0)          //If the condition in the if statement above is false,
//then it will check this condition.
//If true, it will do the commands below
{
Debug.Log(“Player is almost dead!”);
}
else        //else will run it’s command if all conditions above are false
{
Debug.Log(“Player is dead”);
}

Compound Conditional Statements

Compound conditional statements check more than one condition in a single if statement.

Example:  compound if statement using &&

if(health > 0 && health < 50)     //&& = AND,  both conditions must be true
{
Debug.Log(“health is between 1 and 49”);
}

Example:  compound if statement using ||

if(health < 25 || health > 50)     // || = OR,  only one condition must be true
{
Debug.Log(“health is less than 25 or greater than 50”);
}