The Foreach Loop
Learn to use the foreach loop to perform operations on each element of an array or collection.
Introduction
Developers use the foreach
loop in C# and Unity to iterate through the elements of an array or any other collection of items. It allows us to act on each item in the collection without knowing the size of the collection or the index of the current object.
Let’s look at examples of using the foreach
loops in Unity using C#.
Iterating through an array
We can use a foreach
loop to iterate through the elements of an array. Take a look at the example given below:
Press + to interact
int[] numbers = {1, 2, 3, 4, 5};foreach (int number in numbers){Debug.Log(number);}
In this example, the foreach
loop iterates over each item in the numbers
array and logs it to the console using Debug.Log()
. ...