How to do For Each Loops in Unity – C#

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 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 return, or step to the next iteration with continue. You can read more about these loops here.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s