Arrays

Arrays are a numbered/Indexed list of items.

Example:

0   hot dog
1   hamburger
2   pizza
3   dog food
4   meow mix
5   fish food
6  burrito

Arrays start numbering their items at number 0.  In the example above we have a list of 7 items numbered from 0 to 6.

To setup an array you declare a variable and set it as an array.

Example:

string[ ] foodItems;     //arrays are just a variable that can hold a list of the same type of information

The square brackets tell Unity that we want an array not just a single string.

After we attach the script to an object in the scene, we can see the array in the inspector.  To put items in the list we can go into the inspector in Unity and change the length of the array to the number of items we want in the array.  When we do this we will get that many boxes under the array in the inspector – we can type in the item we want in the array in the boxes.

We can also put items into an array in the script when we create the array:

string foodItems[] = {“Pizza”,”Chips”,”Hot wings”,”Soda”};

Getting an item from the array

To get/lookup  an item in the array we need to specify which item we want using the square brackets  [  ].

Example:

Debug.Log(foodItems[3]);  //This will print out the item at position 3 in the foodItems array.  dog food in our example above

Looping through an array

We use loops to go through every position in an array.  For instance, if we want to print out the contents of an array we would do the following:

for(int i = 0; i < foodItems.Length; i++)
{     Debug.Log(foodItems[i]);
}

We start the loop and set i = 0 because 0 is the first line number in an array.  To loop through the entire array we set our condition to i < foodItems.Length.  .Length gives us the length of the array.  The length is how many items are in the array.  In our example above we have a length of 7.  As we loop we print out the item in the array at position i.  i will start at a value of 0 and go until 6.  This will print out all the items.