The foreach loop

The foreach loop is very simple to use. It also has the simplest syntax. We use the foreach keyword followed by brackets in this loop. Inside the brackets, you must specify the type of data you want to iterate through inside your loop. Pick a single element variable name. You can name it whatever you like. This name is used to access this variable inside the main loop block. After the name, we write the in keyword, followed by our List variable name, as shown here:

The foreach loop

I know it's quite confusing now, but don't worry too much about the theory. All you need to know as of now is that the code inside the foreach loop is called as many times as there are elements in myCollectionVariable. So, if myCollectionVariable contains 10 elements, the code inside the loop block (highlighted in pink) will be executed 10 times.

To make it a bit more eye friendly, let's look at an actual code example. We will use the family members example from the previous chapter and print every element inside the loop on Unity Console:

The foreach loop

Write the preceding code, add it as a component to a GameObject, and click on Play. Line 20 creates the loop (foreach familyMember in familyMembers).

Lines 21 to 23 form a loop block. As our List contains four elements, this code block will be executed four times, each time with a different value stored in the familyMember local variable.

Line 22 simply prints the output on Unity Console. Your output should look like this:

The foreach loop

Not that scary, isn't it? Go ahead and play around with the code. You can, for example, add more elements to the familyMembers List.

Alternatively, you can print the number of characters each element has and so on. The sky is the limit! The foreach loop can be used with any type of collection, so there are no issues with using it with an Array, ArrayList, or even Hashtable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset