Time for action – add "else" to the if statement

if-else statements are just like regular if statements with the else option added.

  1. Modify LearningScript as shown in the next screenshot.
  2. Save the file.
  3. In Unity, click on Play.
    Time for action – add "else" to the if statement

Line 14 shows how else, and its code block is simply added after the if code block.

What just happened?

The analysis of code is as follows:

  • The code on line 8 and its description:
    bool theBearMadeBigPottyInTheWoods = false;

    The variable theBearMadeBigPottyInTheWoods is assigned the value of false.

  • The code on line 10 and its description:
    if( theBearMadeBigPottyInTheWoods)

    Since the condition is false, the code block on lines 11 to 13 is not executed, and the script continues to line 14 of the if-else statement.

    Therefore, the code block on lines 15 to 17 is executed instead:

    What just happened?

Pop quiz – understanding if statements

Q1. Humans can answer questions with a yes or no. What do C# if statements need as answers?

Q2. What logical operator can turn a true condition into false, or a false condition into true?

Q3. If two conditions have to be true to make an if statement's code execute, what logical operator would you use to join the conditions?

Q4. If only one of two conditions needed to be true to make an if statement's code execute, what logical operator would you use to join the two conditions?

..................Content has been hidden....................

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