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:
LearningScript
as shown in the next screenshot.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.
I will skip explaining lines of code that are identical in the for
loop example.
The analysis of the code is as follows:
int i = 0;
The initializer is declared and assigned the value of 1.
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.
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.
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.
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.
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.
3.15.34.39