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 )

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:


is the same as


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++)

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.

If you enjoyed reading, try my game Puzzledorf.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

Up ↑

%d bloggers like this: