The while loop

There is one more type of loop that I want to talk about. It has pretty much the simplest form of any loop. The while loop does not create any variable to control its execution. To create a while loop, start with the keyword while, followed by brackets. Within the brackets, you must write a condition. Whenever the condition is true, the code inside the loop block will be executed:

The while loop

It's worth knowing that this is quite a dangerous loop and you need to know how to use it. As a while loop does not create any control variable and is not iterating through the list there is a possible scenario where a condition is always true. This will create an infinite loop—a loop that will go on forever. An infinite loop never finishes executing the loop block, and most certainly, it will crash your program and even Unity Editor.

To avoid this nasty situation—when Unity crashes and we don't even know why—we can use a variable to control the flow of the while loop, like we did in our for loop. Then, this is what the loop looks like:

The while loop

You have seen this before, right? This example contains exactly the same fundamental elements as a for loop. Line 20 is a initializer, and within line 22, we have the i<10 condition. The iterator is on line 26.

Go ahead and type in the code. Try to predict what will happen in the Console Window before you press Play in Editor.

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

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