Loops (C# Programming for Game Development in Unity)

“Beyond the edge of the world there’s a space where emptiness and substance neatly overlap, where past and future form a continuous, endless loop.”

― Haruki Murakami, Kafka on the Shore

Check out this free tutorial covering loops in C#. Learn how to program loops for 3D game development in Unity!

In this tutorial:

Setup

To follow along with this tutorial, you’ll need to open a new Unity project.

Part 1: Introduction to Loops

A great feature of programming is that instead of having to do something over and over again manually, you can use code to automate a task to loop itself over and over again.

Sometimes you want to execute a line of code multiple times. Loops allow you to do so with just one instruction rather than copying and pasting the line.

The best way to learn is by example. Let’s make our first loop!

Part 2: Making Your First C# Loop

Open the script that controls your game, GameController.cs. If you don’t have a Game Controller script, we recommend following our previous tutorial.

Use the following code to create a for loop in the Start method. A for loop is defined with the for keyword, and this type of loop allows you to run code while a condition is met.

Note that in our game example, we have two Log methods left over from our previous tutorial.

void Start () {
Debug.Log (message);
Debug.Log (BuildMessage (1, 2));

for () {

}
}

Awesome! Now we have the basic template set up for a for loop.

There are 3 parts to creating a for loop. First, we need to initialize a variable in the loop’s parentheses. This variable will keep track of how many times the loop will run.

Declaring A Loop’s Index

Part 1: Declare an integer variable i. This is the common name given for the local variable in a for loop because i stands for index.

For loops are often used with arrays (a collection of variables) and the index keeps track of where the loop is in the array at any given time.

Give this i variable the value 0.

for (int i = 0) {

}

Set Conditions of a Loop

Part 2: set up the for loop’s condition, in other words, the conditions required for the for loop to start running or keep running.

Use the following code to set the loop’s condition to i < 10. The loop will only execute its code while the value of i is less than 10. Note that you must separate the 2 parts of the for loop with a semi-colon.

for (int i = 0; i < 10) {

}

Increment the Loop Index

Part 3: We must set up what will happen after the code in the for loop’s scope (between the curly brackets) executes.

Use the following code to increase the value of i each time the loop executes code.

for (int i = 0; i < 10; i++) {

}

i++ will retrieve the value stored in i, increase it by 1, and save it in i. Note that i++ is equivalent to writing i = i + 1.

It’s important to increment the value of the index each time the for loop makes one loop. That way, the value of index will eventually hit the limit, which in this case is 10. Otherwise, the for loop would loop infinitely, you would get a stack overflow error, and your program could crash due to overuse of the compiler.

Set up the Loop’s Scope

Now that the loops conditions are set up, we can add what we want the loop to do at each interval (each time it selects the i variable, checks that i is less than 10, and before it increments i)

In the loop’s scope, call the Log method to print “Loop!”.

for (int i = 0; i < 10; i++) {
Debug.Log ("Loop!");
}

Summary of the For Loop

To summarize: the loop will begin at i = 0. Then the loop will print the message “Loop!”.

Afterward, the loop will increase i by 1. It will print “Loop!” again. The process will repeat until i reaches 10.

Part 3: Testing a Loop in Unity

Let’s prove it! We can test this loop in the Unity console.

Save the script, and open Unity. Press Play.

The Console will show 3 messages. You may be wondering why “Loop!” didn’t print 10 times.

This happened because the Collapse option is selected in the Console window. When the Collapse option is selected, duplicated messages are shown as 1 message.

screenshot of the unity console with the collapse button
This is the Unity Console with the mouse pointing at the console button.

However, you can see the number of times the message prints on the right-hand side of the Console window. “Loop!” printed 10 times. You can also click on “Collapse” to see all 10 messages.

Press Stop. Next up, we’ll use the for loop we created to keep track of a player’s score.

Part 4: Keeping Track of a Player’s Score

Another thing you can use a loop for is to keep track of a user’s score.

Open GameController.cs. Above the loop, create an integer variable named scoreCounter. Give it the initial value 0.

scoreCounter = 0;
for (int i = 0; i < 10; i++) {
Debug.Log ("Loop!");
}

In the loop, increase the value of scoreCounter by 100 every time the loop runs.

scoreCounter = 0;
for (int i = 0; i < 10; i++) {
scoreCounter = scoreCounter + 100;
Debug.Log ("Loop!");
}

Change the the Log method to print the player’s score rather than “Loop!”

scoreCounter = 0;
for (int i = 0; i < 10; i++) {
scoreCounter = scoreCounter + 100;
Debug.Log ("Your score is " + scoreCounter);
}

Testing the Score Counter

Let’s test this score counter! Save the script, and open Unity. Press Play. The Console will print different values of the score by increments of 100 up until the score is 1000. Press Stop.

Note About Infinite Loops

One thing that is important with loops is that you must ensure that the loop will end at some point. Suppose you replaced i++ with i–. The value of i would decrease and therefore never reach 10. You do not want to make infinite loops like these because they cause games to crash.

Infinite loops are easy to create in a second type of loop: the while loop.

Part 5: Making a While Loop in C#

A while loop is like a for loop but is formatted differently.

Let’s make a while loop. In GameController.cs, delete the for loop.

Like a for loop, a while loop can run code while a condition is met. First you need to create a condition as a Boolean variable. A Boolean variable can have 1 of 2 values: true or false.

You could explicitly say true or false, like in the following code. Alternatively, you can use a statement that is true or false, such as “5 = 5” or “5 < 3”.

void Start () {
Debug.Log (message);
Debug.Log (BuildMessage(1, 2));

bool condition = true;
}

Similar to the for loop, use the while keyword followed by parentheses and curly brackets to define a while loop. Next, pass the condition variable as the parameter of a while loop. The condition must be met for the loop to start or keep looping.

void Start () {
Debug.Log (message);
Debug.Log (BuildMessage(1, 2));

bool condition = true;
while (condition) {

}
}

If the condition is met, the while loop’s code will execute. This will repeat until condition is false. If the condition is false, the while loop’s code will be skipped.

Printing with the While Loop

In the while loop, call the Log method to print “While loop!”. Then set condition to false. This way, the condition’s value will not be true forever, and we will avoid having an infinite loop.

while (condition) {
Debug.Log ("While loop!");
condition = false;
}

Testing a While Loop

Let’s Save the script, and open Unity. Press Play. The message “While loop!” will only print once.

Press Stop. Let’s look at another use of the while loop, with the help of the Random class.

Part 6: Printing a Random Number of Times

Suppose we wanted to print “While loop!” a random amount of times. Open GameController.cs. In the loop, use the following code to set the value of condition randomly.

while (condition) {
Debug.Log ("While loop!");
Random.Range(0, 100) > 10;
}

Use The Random Class

Range is a function of the Random class that chooses a random number between the 2 numbers specified as its parameters. If the number randomized is greater than 10, condition’s value will be true. If the number randomized is less than 10, condition’s value will be false.

Suppose Random.Range chose 8 as the number. 8 is not greater than 10, so condition would equal false because the statement is false. Thus, with every iteration of the loop, there is a 10 percent chance that condition will become false and the loop will exit.

This chance logic is useful for when you want to spawn objects for the player or spawning enemies, for example.

Congratulations! You’ve built your first for and while loops for game development in C#.

Review

—Team Mammoth from Mammoth Interactive INC. Tutorial by Glauco Pires and Transcribing by Alexandra Kropova

Liked this tutorial? Get a free game development video course!

More resources on this topic:

Leave a Reply

Your email address will not be published. Required fields are marked *