How to do For Each Loops in – Unity C#

For each loops are a common thing in C# and very helpful for your Unity projects. I used them frequently in Puzzledorf, for example, to loop over all of the objects that can be moved in a level.

For each loops in C# and Unity look like the following.

foreach (GameObject flame in flameList )
{
  flame.SetActive(false);
}

In this example, we have an array of Game Objects called flameList. This loop will go through every element in the array (all of our flames) and set each one to inactive.

It goes in the format of:

foreach ( type_of_variable    iterator_name    in    array_to_search)
{
     iterator_name = something;
}

When you do this kind of foreach loop, you are declaring the type of variable you want to search for in the array. It has to be the same variable type that’s contained in the array. You then give an iterator name, so that whenever you refer to that iterator, you are referring to the current element in the array that you’ve looped to. Effectively:

flame.SetActive(false);

is the same as

flameList[i].SetActive(false);

The iterator, ‘item’ in this case, becomes the value you have looped to currently. In other words, referring to the iterator is the equivalent of a regular for loop like this:

for (int i = 0; i < flameList.Count; i++)
{
  flameList[i].SetActive(false);
}

Foreach loops will work on many different types of arrays such as standard arrays, vectors, lists and others.

You can break out of a foreach loop at any time with break, or step to the next iteration with continue. Calling return will also take you out of the function, not just the loop. You can read more about these loops here.

Leave a comment

Blog at WordPress.com.

Up ↑