Time for action – using foreach loops to retrieve data
We're going to create an array, a list and a dictionary, then loop through each one to retrieve the desired data from each one by using foreach
loops.
Modify
LearningScript
as shown in the next screenshot.Save the file.
In Unity, click on Play.
What just happened?
As we looped through each list, we decided which data to display to the Console:
The analysis of the code is as follows:
For each list we created, we populated them using a Collection Initializer.
The code between lines 9 and 10 with its description:
string[] ponyArray = new string[] {"AppleJack", "Rarity"};
A
string
array namedponyArray
is declared and two strings are added.The code on line 12 with its description is as follows:
foreach(string pony in ponyArray)
A
foreach
loop is used to retrieve one element, a pony name string, stored inponyAr
ray
.A variable is declared named
pony
to hold the retrieved pony name.Once a pony name is retrieved, the
foreach
code block, lines 13 to...