Day 16 — It’s time to talk about loops in Unity

Hey and welcome!

Loops are an incredibly fundamental tool with C# and in programming in general as they allow us to iterate through bulk data or create instances where we want the same line of code to run either infinitely or for a certain number of times depending on the loop and the situation.

Let’s have a chat about the for () loops first. These loops along with their counterparts the foreach () loop are handy for iterating through the data contained in arrays and collections however we’ll be covering those in their own topic at a later time. So what can we do with a for () loop in the meantime to show off what it’s capable of?

Well I’ve got 20 apples on me because I really like apples and I want to print a message out to the console each time one of my precious apples is taken away from me.

To do this without a loop we would be looking at something insane like this:

private int _myApples = 20;

Pretty tedious looking right? Well we can do this in a lot less lines of code with a for loop.

void Start()
for (int _myApples = 20, _myApples > 0; myApples--)
Debug.Log("I have " + _myApples + " left.");

There we go, much cleaner looking, I’m not even mad that all of my apples have been taken. Now let’s break this down, to begin with in our condition for the for loop we’re declaring an index called _myApples and assigning it the value of 20. This could be renamed to anything but is commonly written as i and is used to tell the loop how many times we want to iterate through the line of code usually, in this case it’s 20 times.

Then we have _myApples is greater than 0 which is a true statement so the loop will keep going for 20 times, if this value was 1 then the loop would run 19 times etc. Then lastly we have a decrement setup so that it takes 1 off of the value of _myApples everytime we loop in and run the code once until the value of _myApples is 0 and the loop stops.

Then we simply have the message that we’re printing in the code that gets used 20 times thanks to the condition of the loop. It should be noted that the more common and well known syntax for the for loop is for (i = 0; i < 5; i++) which would loop 5 times over but I decided to play about to show what can be done with it.

OK let’s talk about a do while loop real quick before we move onto the last loop. Now this is an interesting one but admittedly I haven’t figured out many applications for it since I find most of the time that whatever I’m thinking of I can just put into a while loop.

What makes this interesting is that regardless of what we pass into the condition for the while part the do part will always run the code within the {} at least once, even if it’s a false statement. So if we had the following:

Debug.Log("Hey check me out");
} while (0 > 1);

It would still print out “Hey check me out” at least once into the console even though 0 is not greater than 1.

Right now onto the last loop which is the while loop. I showed this one off in the enemy spawning article when we needed to set up an infinite loop so that our enemies could spawn in continuously but here I’m going to show off a non-infinite application for it.

Let’s say we have a car in our game and we’re needing to handle the acceleration for it until it hits it’s top speed of 150mph. We can’t exactly create a speed variable and assign the number 150 and get the player to make use of that when they press the accelerator button since a car doesn’t go from 0 to 150 in less than a second (yet).

So let’s put our knowledge of loops to good use here and create some reasonable acceleration:

private int _topSpeed = 150;
private int _speed;

Let’s look at what’s happening in our while loop first, we’re incrementing the value of 5 into our _speed variable and we’re making use of a yield to pause execution for 0.5 seconds meaning that our speed will be increasing by 5 every 0.5 second. That’s pretty reasonable acceleration we have now.

Lastly our condition for the while loop is checking to make sure that so long as our _topSpeed is greater than our _speed variable the condition will be true. Since our _topSpeed has been set to 150 our loop will keep going and our speed will keep increasing until it reaches 150 and at that point the _topSpeed will no longer be greater than our _speed so the while loop will then stop execution.

I could honestly keep waffling on for thousands of more words about loops, that’s how important I think they are and they’ll certainly be reappearing in future articles but I’ll end things here for you to think of your own applications with loops.

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.