While loops and Infinite loops in Unity!

Objective: Define and implement while loops and infinite loops.

While loop is a loop used to make recurring actions and can be used to create infinite loops.

An infinite loop is a loop that repeats forever, as long as the program is active. An infinite loop is also dangerous. If you do not set a condition or a yield to slow down or stop the infinite loop, it will eat all the memory you have and lock up, or crash Unity.

A while loop looks like this.

You place the condition inside the parentheses and the action code below.

If you are going to make an infinite loop you will need to place the loop inside a coroutine (IEnumerator)

The IEnumerator allows you to use the function yield, this give your computer the breathing room it needs to not be consumed by the infinite loop. The condition will also need to be set to true.

This will print out do something once every second, forever.

If you are not using the infinite loop method, then you will need to set a condition for the while loop to exit.

If the variable is lower than the set max the while loop will repeat until the statement is no longer true, so we need to increment the variable every time the while loop cycles.

That’s it, the while loop has an exit and will not run past the maxed value. Now we know how to properly work with while loops, and how to successfully use an infinite loop, however I would advise caution and think of an alternative. Never be afraid to experiment with your code, and I’ll see you in the next tutorial.