Time for action – create a couple of if statements

The if statements work by determining whether a condition inside a pair of parentheses is true or false.

  1. Modify LearningScript as shown in the next screenshot.
  2. Save the file.
  3. In Unity, click on Play.
Time for action – create a couple of if statements

What just happened?

Here's the output in the Unity Console:

What just happened?

Code analysis:

  • The code on line 8 is as follows:
    bool theBearMadeBigPottyInTheWoods = true;

    This Boolean variable is declared and assigned the value of true.

  • The code on line 10 and its description:
    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.

Using the NOT operator to change the condition

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.

  • The code on line 15 along with its description:
    theBearMadeBigPottyInTheWoods = false;

    Assigns the value false to theBearMadeBigPottyInTheWoods.

  • The code on line 17 with its description is as follows:
    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.

Checking many conditions in an if statement

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:

  • AND: It is used by putting && between the conditions being checked.
  • OR: It is used by putting || between the conditions being checked.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.96.86