Iteration Statements — Unity C#

Imran Momin
6 min readApr 20, 2021

--

What do we do when we need to go through the entire collection element by element? This is called Iteration and C# provides several statement types that let us loop through collection elements.

Iteration statements are like methods, in that they store a block of code to be executed; unlike methods, they can repeatedly execute their code blocks as long as their conditions are met.

For Loops

The for loop is most commonly used then a block of code needs to be executed a certain number of times before the program continues. The statement itself takes in three expressions, each with a specific function to perform before the loop executes. Since for loops keep track of the current iteration, they are best suited to arrays and lists.

for(initializer; condition; iterator)
{
code block;
}

Let’s break this down:

· The for keyword starts the statement, followed by a pair of parentheses.

· Inside the parentheses are the gatekeepers: the initializer, condition, and the iterator expressions.

· The loop starts with the initializer expression, which is a local variable created to keep track of how many times the loop has executed — this is usually set to 0 because collection types are zero-indexed.

· Next, the condition expression is checked and, if true, proceeds to the iterator.

· The iterator expression is used to either increase or decrease (increment or decrement) the initializer, meaning the next time the loop evaluates its condition, the initializer will be different.

questPartyMembers — Example

· First, the initializer in the for loop is set as a local int variable named i with a starting value of 0.

· To ensure we never get an out-of-range exception, the for loop makes sure that the loop only runs another time if i is less than the number of elements in questPartyMembers.

· Finally, i is increased by 1 each time the loop runs with the ++ operator.

· Inside the for loop, we have printed out the index and the list element at that index using i. Notice that i is in step with the index of the collection elements since both starts at 0.

Finding an element — Example

While we loop through the questPartyMembers, let’s see whether we can identify when a certain element is iterated over and add a special debug log just for that case:

The console output looks almost the same, except that there is now an extra debug log — one that only printed once when it was Merlin’s turn to go through the loop. More specifically, when “i” was equal to 1 on the second loop, the if statement fired and two logs were printed out instead of just one.

foreach loops

foreach loops take each element in a collection and store it in a local variable, making it accessible inside the statement. The local variable type must match the collection element type to work properly. foreach loops can be used with arrays and lists, but they are especially useful with dictionaries, as they are not based on a numeric index.

foreach(elementType localName in collectionVariable)
{
code block;
}

We can break this down as follows:

· The element type is declared as a string, which matches the values in questPartyMembers.

· A local variable, called partyMember, is created to hold each element as the loop repeats.

· The “in” keyword, followed by the collection we want to loop through in this case, questPartyMembers, finishes things off:

Looping through key-value pairs

To capture a key-value pair in a local variable, we need to use the aptly-named KeyValuePair type, assigning both the key and value types to match the dictionary’s corresponding types. Since KeyValuePair is its type, it acts just like any other element type, as a local variable.

For example, let’s loop through itemInventory dictionary and debug each key-value like a shop item description:

The keys are strings and the values are integers, which we can print out as the item name and item price:

While loops

While loops are similar to if statements in that they run as long as a single expression or condition is true. Value comparisons and Boolean variables can be used as while conditions, and they can be modified with the NOT operator.

While my condition is true, keep running my code block indefinitely:

initializer
while(condition)
{
code block;
iterator;
}

With while loops, it’s common to declare an initializer variable, as in a for loop, and manually increment or decrement it at the end of the loop’s code block. Depending on the situation, the initializer is usually part of the loop’s condition.

Tracking player lives — Example

Let’s take a common use case where we need to execute code while the player is alive, and then debug when that’s no longer the case:

  1. Create a initializer variable, called playerLives, of the int type, and set it to 3.
  2. Declare a while loop with the condition checking whether playerLives is greater than 0 (that is, the player is still alive).
  3. Inside the while loop, debug something to let us know the character is still kicking, then decrement playerLives by 1 using the “--” operator.
  4. Add a debug log after the while loop curly brackets to print something when our lives run out:

With playerLives starting out at 3, the while loop will execute three times. During each loop, the debug log, “Still alive !”, fires, and a life is subtracted from playerLives, When the while loop goes to run a fourth time, our condition fails because playerLives is 0, so the code block is skipped and the final debug log prints out:

To infinity and beyond

We need to understand one extremely vital concept when it comes to iteration statements: infinite loops. These are exactly what they sound like: when a loop’s conditions make it impossible for it to stop running and move on in the program.

Infinite loops usually happen in for and while loops when the iterator is not increased or decreased; if the playerLives line of code was left out of the while loop example, Unity would freeze and/or crash, recognizing that playerLives would always be 3 and execute the loop forever.

Iterators are not the only culprits to be aware of; setting conditions in a for loop that will never fail, or evaluate to false, can also cause infinite loops.

--

--

Imran Momin
Imran Momin

Written by Imran Momin

A VR/AR developer, who enjoys making games and developing interactive environments using Unity’s XR integration toolkit for Oculus quest and HTC vive devices.

No responses yet