Time for action – selecting a pony from a List using a for loop
Let's add four pony names to a List
. Retrieve and display the number of elements in the List
. Then use a for
loop to display each pony name, and select one of them:
Modify
LearningScript
as shown in the next screenshot.Save the file.
In Unity, click on Play.
What just happened?
The following screenshot shows the number of elements in ponyList
, the names of the ponies we added to ponyList
, and the pony we were looking for:

The analysis of the code is as follows:
The code between lines 8 and 9 with its description:
List<string> ponyList = new List<string>() {"Princess Cadence", "Fluttershy", "Rainbow Dash", "Rarity"};
A
List
namedponyList
is declared that will store thestring
type.Four strings are added of the pony names.
The code on line 11 with its description is as follows:
Debug.Log("Number of elements in ponyList: " + ponyList.Count);
The string
Number of elements in ponyList:
plus the number of elements used inponyList...