Time for action – finding data and breakout of the while loop

We're going to do something a little different in this loop. Once we find the pony we want, we'll breakout of the while loop. This is handy when looping through a large list of objects. When the desired data is found, there's no sense in continuing to loop through the rest of the list:

  1. Modify LearningScript as shown in the next screenshot.
  2. Save the file.
  3. In Unity, click on Play.
Time for action – finding data and breakout of the while loop

What just happened?

If we have been searching for Fluttershy instead of Rainbow Dash, and not included the break keyword on line 19, the output would have been exactly the same as the for loop example. In fact, the break keyword could have also have been used to breakout of the for loop.

What just happened?

I will skip explaining lines of code that are identical in the for loop example.

The analysis of the code is as follows:

  • The code on line 11 with its description is as follows:
    int i = 0;

    The initializer is declared and assigned the value of 1.

  • The code on line 12 with its description is as follows:
    while(i < ponyList.Count)

    The while loop is declared with the condition.

    Since i is 0, it is less than ponyList.Count, which is 4, the condition is true.

    The while loop code block (that is, lines 13 to 22), is executed.

  • The code on line 16 with its description is as follows:
    if(ponyList[i] == "Rainbow Dash")

    During each iteration through the code block, this if statement is checking to see if the name retrieved from ponyList is equal to Rainbow Dash.

    When it is, the code block of lines 17 to 20 is executed.

    When it isn't, line 21 is the next line that is executed.

  • The code on line 21 with its description is as follows:
    i++;

    The iterator i is incremented by 1 and the loop repeats back to line 12 to check the condition again.

    The loop repeats until i is equal to 4, making the condition false which exits the loop.

  • The code on line 18 with its description is as follows:
    Debug.Log("Stop. I was looking for " + ponyList[i]);

    The string Stop. I was looking for plus the name Rainbow Dash is displayed in the Console.

  • The code on line 19 with its description is as follows:
    break;

    break is a C# keyword that alters code flow.

    Code execution immediately leaves this while loop code block and continues to the first statement following the code block.

    There is no statement following the while loop, the script is finished.

Have a go hero – changing the pony name being searched

On line 16, change the pony name being searched and observe how it changes the number of pony names displayed in the Console before stopping.

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

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