If-else Statements — Unity C#
If-else statements are the most common way of making decisions in code. When stripped all of its syntax, the basic idea is if my condition is met, execute this block of code; if it’s not, execute this other block of code. Think of these statements as gates, or doors, with the conditions as their keys. To pass through, the key needs to be valid. Otherwise, entry will be denied and the code will be sent to the next possible game.
Basic syntax
A valid if-else statement requires:
· The “if” keyword at the beginning of the line
· A pair of parentheses to hold the condition
· A statement body.
if(condition is true)
Execute this line of code
However, if the statement body is more than a single line, it needs to have a pair of curly brackets to hold the bigger code block.
if (condition is true)
{
Execute multiple lines of code
}
Optionally, an else statement can be added to store the action you want to take when the if statement condition fails. The same rules apply to the else statement.
else
Execute this line of code
//OR
else
{
Execute multiple lines of code
}
In blueprint form, the syntax almost reads like a sentence.
if (condition is true)
{
Execute this of code
}
else
{
Execute this block lines of code
}
Since these are great introductions to logical thinking, at least in programming, we will break down the three different if-else variations in more detail:
- A single if statement can exist by itself in cases where you don’t care about what happens if the condition isn’t met. In the following example, if hasDungeonKey is set to true, then a Debug.Log will print out; if it set to false, no code will execute.
2. Add an else statement in cases where action needs to be taken whether the condition is true or false. If hasDungeonKey were false, the if statement would fail and the code execution would jump to the else statement.
3. For cases where you need to have more than two possible outcomes, add an else-if statement with its parentheses, conditions, and curly brackets.
Thieving prospects — Example:
Let’s write an if-else statement that checks the amount of money in a character’s pocket, returning different debug logs for three different cases: greater than 50, less than 15, and anything else.
- Open up the script and add a new int variable, named currentMoney. Set its value to between 1 and 100.
- Declare an if statement to check whether currentMoney is greater than 50, and print a message to the console if this is true.
- Add an else-if statement to check whether currentMoney is less than 15 with a different Debug.Log.
- Add an else statement with no condition and a final default lof.
- Save the file and click on Play.
With currentMoney set to 45 in the above example, we can break down the code sequence as follows:
- The if statement and debug are skipped because currentMoney is not greater than 50.
- The else-if statement and debug log are also skipped because currentMoney is not less than 15.
- Since neither of the previous conditions was met, the else statement executes and the third debug log is displayed.
Using the NOT operator
Use cases won’t always require checking for a positive, or true, condition, which is where the NOT operator comes in. Written with a single exclamation point, the NOT operator allows for negative, or false, conditions to be met by if or else-if statements. This means that the following conditions are the same.
if(variable == false)
//AND
if(!variable)
As you already know, you can check for boolean values, literal values, or expressions in an if condition. So, naturally, the NOT operator has to be adaptable. Take a look at the following example of two different negative values, hasDungeonKey and weaponType, used in an if statement.
We can evaluate each statement as follows:
- The first statement can be translated to, “if hasDungeonKey is false, the if statement evaluates to true and executes its code block.”
- The second statement can be translated to, “if the string value of weaponType is not equal to Sword, then execute this code block.”
Evaluating multiple conditions
It is also possible to combine multiple condition checks into a single if or else-if statement with AND and OR logic operators.
AND is written as &&. Any condition using the AND operator means that all conditions need to evaluate to true for the if statement to execute.
OR is written as ||. An if statement using OR operator will execute if one or more of its conditions is true.
Reaching the treasure — Example:
- Declare three variables: pureOfHeart is a bool and should be true; hasSecretIncantation is also a bool and should be false, and rareItem is a string with its value Diamond.
- Create a public method with no return value, called OpenTreasureChamber, and call it inside Start().
- Inside OpenTreasureChamber, declare an if-else statement to check whether pureOfHeart is true and that rareItem matches the string value.
- Create a nested if-else statement inside the first, checking whether hasSecretIncantation is false.
- Add debug logs for each if-else case, save, and click on Play.
If you matched the variable values to the preceding screenshot, the nested if statement debug log will be printed out. This means that our code got past the first if statement checking for two conditions, but failed the third.