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:

Get hands-on with 1200+ tech skills courses.