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:
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 a 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 the 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...