Time for action – create if statements with more than one condition to check

  1. Modify LearningScript as shown in the next screenshot.
  2. Save the file.
  3. In Unity, click on Play.
    Time for action – create if statements with more than one condition to check

Note

Notice line 11 is using the AND operator, and line 16 is using the OR operator.

What just happened?

Here is the output you get in the Unity Console:

What just happened?

Code analysis:

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

    A bool variable is declared and assigned the value of true.

  • The code on line 9 with its description:
    int temperature = 40;

    An int variable is declared and assigned the value 40.

  • The code on line 11 with its description:
    if(temperature >= 35 &&  theBearMadeBigPottyInTheWoods)

    An if statement to test if both conditions are true.

    The first test is checking if the temperature is greater then, or equal to, 35.

    The value stored in temperature is 40, so this condition is true.

    The value stored in theBearMadeBigPottyInTheWoods is true. Therefore the first condition and the second condition are true, so the code block executes.

  • The code on line 16 with its description:
    if(temperature >= 35 || theBearMadeBigPottyInTheWoods)

    An if statement to test if either of the conditions are true.

    We already know that both the conditions are true, and either the first condition or the second condition needs to be true. Therefore the code block will execute.

Have a go hero – change the value assigned to temperature

Try changing temperature to a lower value such as 30. Only one of the if statements will be true:

Have a go hero – change the value assigned to temperature

The following is the analysis of code:

  • The code on line 11 and its description is as follows:
    if(temperature >= 35 && theBearMadeBigPottyInTheWoods)

    Only one of the conditions is now true, as 30 is not greater then, or equal to, 35.

    Therefore the first condition is false. Since both conditions have to be true, the code block does not execute.

  • The code on line 16 and its description:
    if(temperature >= 35 || theBearMadeBigPottyInTheWoods)

    Only one of the conditions is now true.

    30 is not greater then or equal to 35, therefore the first condition is false.

    The second condition is true.

    Since only one of the two conditions has to be true, doesn't make any difference which one, the code block executes.

Have a go hero – change theBearMadeBigPottyInTheWoods to false

Now change theBearMadeBigPottyInTheWoods to false as well. Now you see that neither of the if statements will execute their code blocks.

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

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