Retrieving the data from the Array or List<T>

Declaring and storing data in the array or list is very clear to us now. The next thing to learn is how to get stored elements from an array. To get a stored element from the array, write an array variable name followed by square brackets. You must write an int value within the brackets. That value is called an index. The index is simply a position in the array. So, to get the first element stored in the array, we will write the following code:

myArray[0];

Unity will return the data stored in the first place in myArray. It works exactly the same way as the return type methods that we discussed in the previous chapter. So, if myArray stores a string value on index 0, that string will be returned to the place where you are calling it. Complex? It's not. Let's show you by example.

Note

The index value starts at 0, not 1, so the first element in an array containing 10 elements will be accessible through an index value of 0 and last one through a value of 9.

Let's extend the familyMembers example:

Retrieving the data from the Array or List<T>

I want to talk about line 20. The rest of it is pretty obvious for you, isn't it? Line 20 creates a new variable called thirdFamilyMember and assigns the third value stored in the familyMembers list. We are using an index value of 2 instead of 3 because in programming, counting starts at 0. Try to memorize this; it is a common mistake made by beginners in programming.

Go ahead and click on Play. You will see the name Adam being printed in the Unity Console. While accessing objects stored in an array, make sure you use an index value between zero and the size of the array. In simpler words, we cannot access data from index 10 in an array that contains only four objects. Makes sense?

Checking the size

This is very common—we need to check the size of the array or List. There is a slight difference between a C# Array and List<T>.

To get the size as an integer value, we write the name of the variable, then a dot, and then Length of an array or Count for List<T>.

  • arrayName.Length: This returns a integer value with the size of the array
  • listName.Count: This returns a integer value with the size of the list

As we need to focus on one of the choices here and go ahead, from now on, we will be using List<T>.

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

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