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:
LearningScript
as shown in the next screenshot.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:
List<string> ponyList = new List<string>() {"Princess Cadence", "Fluttershy", "Rainbow Dash", "Rarity"};
A List
named ponyList
is declared that will store the string
type.
Four strings are added of the pony names.
Debug.Log("Number of elements in ponyList: " + ponyList.Count);
The string Number of elements in ponyList:
plus the number of elements used in ponyList
is displayed in the Console.
ponyList.Count
is using dot syntax to access the Count
property, a variable that stores the number of elements in a List
.
Four names were added to ponyList
, so it has four elements to store the string names.
for(int i = 0; i < ponyList.Count; i++)
The for loop
is created.
The initializer is simply a declared variable that's assigned a value.
We declared a variable i
of type int
, and assigned it the a value of 0
. Why?
The first index number in a List
is 0
.
The condition is checked for true before the code block, lines 14 to 19, is allowed to be executed.
When our for
loop first begins, the variable i
is equal to 0
, and ponyList.Count
is equal to 4
, therefore 0
is less than 4
, which is true
. Therefore the for
loop code block is allowed to execute.
The iterator, i++
, now adds 1 to i
, making i
now equal to 1
.
i++
is the same thing as writing i = i + 1
, which means that you are taking the value in i
and adding 1, then assigning that to i
.
The loop repeats until the condition becomes false
.
After four times through the loop, i
is now equal to 4, therefore the condition is now false
because i
is not less than 4
, so the loop is finished.
Debug.Log(ponyList[i]);
The elements in ponyList
are being access using the index number.
As the for
loop is executed for the first time, i
is equal to 0
, therefore
ponyList[i]
is actually ponyList[0]
, the element at index 0.
The element at index 0 is storing Princess Cadence
.
After each iteration through the for
loop, 1 is added to i
, therefore the next trip through the for loop, i
will be 1.
ponyList[i]
will actually be ponyList[1]
, the next element at index 1.
The result is all four ponies will be accessed and displayed in the Console.
if(ponyList[i] == "Fluttershy")
During each iteration through the code block, this if statement is checking to see if the name retrieved from ponyList
is equal to "Fluttershy"
.
When it is, line 18 is executed.
Debug.Log("I was looking for " + ponyList[i]);
The string I was looking for
plus the name Fluttershy
is displayed in the Console.
3.145.109.8