Create a List
that stores the names of some ponies. Since they are names, use the string
type.
LearningScript
as shown in the next screenshot.The following screenshot is the Console output. Notice the first output tells you there is a total of 3 elements in the List
:
The analysis of code is as follows:
Using System.Collections.Generic;
To be able to use a List
, this tells Unity where to find the necessary C# code files for using a List
.
Change the using statement to using System.Collections.Generic;
.
List<string> myFavoritePonies = new List<string>();
This statement creates an empty L
ist
object.
First thing to notice is that List<string>
specifies that you are creating a List
of type string
.
The name of the List
is myFavoritePonies
.
Everything on the left side of the assignment operator (=
) is creating a variable, declaring the type and the name.
Everything on the right side is just like assigning a value to a variable, therefore new List<string()
is a method called to create a new List
object in computer memory, and give that memory location the name of myFavoritePonies
.
myFavoritePonies.Add("Princess Cadence");
These three lines of code are adding strings
, the pony names, to the myFavoritePonies
List
.
Just like an array, each pony name string
added is given an index number for the element that each pony name is stored in:
Debug.Log("This List has " + myFavoritePonies.Count + " ponies");
myFavoritePonies.Count
retrieves the number of elements in the List
.
Debug.Log("The pony's name at index 1 is " + myFavoritePonies[1]);
Here you see the index number inside square brackets. Just like an array, this is how to directly retrieve the data in an element at a specific index.
Add another pony to the List
, then display it's name. Also, in the Console, display the number of elements in the List
after adding the fourth pony.
A dictionary has a Key/Value pair. The Key is just like an index in an array or list, it's associated with a particular value. The big benefit of a dictionary is that we can specify what the key is going to be. We have to specify the type and the name of the key that will be associated with the value stored.
A real world example you're familiar with is a collection of customers and their ID number. Just by knowing the customer's ID, you could retrieve the customer's information.
18.226.4.191