The if statements work by determining whether a condition inside a pair of parentheses is true or false.
LearningScript
as shown in the next screenshot.Here's the output in the Unity Console:
Code analysis:
bool theBearMadeBigPottyInTheWoods = true;
This Boolean variable is declared and assigned the value of true
.
if( theBearMadeBigPottyInTheWoods)
An if
statement to test if the condition between the parenthesis is true
or false
.
The variable theBearMadeBigPottyInTheWoods
is storing a value true
, therefore.The code block on lines 11 to 13 is executed, as shown in the Console screenshot.
Here's a little curveball to wrap your mind around, the NOT logical operator. It's written in code using an exclamation mark. This makes a true condition false, or a false condition true.
theBearMadeBigPottyInTheWoods = false;
Assigns the value false
to theBearMadeBigPottyInTheWoods
.
if( ! theBearMadeBigPottyInTheWoods)
Another if statement, but this time theBearMadeBigPottyInTheWoods
is false.
However, there's a NOT logical operator in front of the variable. See the exclamation mark in the red circle shown in the previous screenshot.
This means the if statement condition is NOT false, which is the same as saying true. Therefore the code block on lines 18 to 20 will be executed, as shown in the Console screenshot
The code block on lines 18 to 20 will be executed, as shown in the Console screenshot
I can already hear your question, why not just check for true? As you will discover when writing if statements, you need to be able to make decisions based on whether a condition is true, or if the condition is false. You want the option to execute a code block for either of these two conditions. For example, you may want to execute some code based on whether a user didn't press a button at a particular time. If the user did not press the button, then execute the code block.
Sometimes you will want your if statements to check many conditions before any code block is executed. This is very easy to do. There are two more logical operators that you can use:
&&
between the conditions being checked.||
between the conditions being checked.3.129.70.185