Arrays and Lists— Unity C#

Imran Momin
5 min readApr 17, 2021

--

Arrays

Arrays are the most basic collection that C# offers. Think of them as containers for a group of values, called elements in programming terminology, each of which can be accessed or modified individually.

· Arrays can store any type of value; all the elements need to be of the same type.

· The length, or the number of elements, an array can have is set when it’s created.

· If no initial values are assigned when it’s created, each element will be given a default value. Arrays storing number types default to zero, while any other type gets set to null or nothing.

Arrays are the least flexible collection type in C#. This is mainly because elements can’t be added or removed after they have been created. However, they are particularly useful when storing information that isn’t likely to change. That lack of flexibility makes them faster compared to other collection types.

Basic Syntax

· Array variables require a specified element type, a pair of square brackets, and a unique name.

· The new keyword is used to create the array in memory, followed by the value type and another pair of square brackets.

· The number of elements the array will store goes inside the second pair of square brackets.

elementType[] name = mew elementType[numberOfElements];

Let's take an example where we need to score the top three high scores in our game:

int topPlayerScores = new int[3];

Broken down, topPlayerScores is an array of integers that will store three integer elements. Since we didn’t add any initial values, each of the three values in topPlayerScores is 0.

You can assign values directly to an array when it’s created by adding them inside a pair of curly brackets at the end of the variable declaration.

//Longhand initializer
int[] topPlayerScores = new int[] {313, 549, 984};
//Shorthand initializer
int[] topPlayerScores = {313, 549, 984};

Indexing and subscripts

Each array element is stored in the order it’s assigned, which is referred to as its index. Arrays are zero-indexed, meaning that the element order starts at zero instead of one. Think of an element’s index as its reference, or location. In topPlayerScores, the first integer, 313, is located at index 0, 549 at index 1, and 984 at index 2.

Individual values are located by their index using the subscript operator, which is a pair of square brackets that contains the index of the elements. For example, to retrieve and store the second array element in topPlayerScores, we would use the array name followed by subscript brackets and index 1.

// The value of score is set to 549
int score = topPlayerScores[1];

The subscript operator can also be used to directly modify an array value just like any other variable, or even passed around as an expression by itself.

topPlayerScores[1] = 1200;
Debug.Log("topPlayerScores[1]");

The values in topPlayerScores are now 313, 1200, and 984.

Range Exceptions:

When arrays are created, the number of elements is set and unchangeable, which means we can’t access an element that doesn't exist. In the topPlayerScores example, the array length is 3, so the range of valid indices is from 0 to 2. Any index of 3 or higher is out of the array’s range and will generate an aptly named IndexOutOfRangeException in the console.

Lists

Lists are closely related to arrays, collecting multiple values of the same type in a single variable. They are much easier to deal with when it comes to adding, removing, and updating elements, but their elements aren’t stored sequentially. This can sometimes lead to a higher performance cost over arrays.

Basic Syntax

A List-type variable needs to meet the following requirements:

· The List keyword, its element type inside left and right arrow characters, and a unique name.

· The new keyword to initialize the list in memory, with the List keyword and element type between arrow characters.

· A pair of parentheses capped off by a semicolon.

List<elementType> name = new List<elementType>();

Like arrays, lists can be initialized in the variable declaration by adding element values inside a pair of curly brackets.

List<elementType> name = new List<elementType>(){value1, value2};

Elements are stored in the order they are added, are zero-indexed, and can be accessed using the subscript operator.

Party members — Example

  1. Create a list of the string type, called questPartyMembers, and initialize it with the names of three characters.
  2. Add a debug log to print out the number of party members in the list using the Count method.
  3. Save the file and Play it in Unity.

We initialized a new list that holds three sting values, and used the count method from the List class to print out the number of elements:

Common Methods

List elements can be accessed and modified like arrays with a subscript operator and index, as long as the index is within the List class’s range. However, the List class has a variety of methods that extend its functionality, such as adding, inserting, and removing elements. Sticking with the questPartyMembers list, let’s add a new member to the team:

questPartyMembers.Add("Craven");

The Add method appends the new element at the end of the list. which brings the questPartyMembers count to four and the element order to the following:

{"Grim", "Merlin", Sterling", "Craven"};

To add an element to a specific spot in a list, we can pass the insert method the index and the value that we want to add.

questPartyMembers.Insert(1, "Tanis");

When an element is inserted at a previously occupied index, all the elements in the list have their indices increased by 1.

{"Grim", "Tanis", "Merlin", Sterling", "Craven"};

Removing an element is just as simple; all we need is the index or the literal value, and the List class does the work.

// Both of these methods would remove the required elementquestPartyMembers.Remove(0);questPartyMembers.Remove("Grim");

At the end of our edits, questPartyMembers now contains the following elements indexed from 0 to 3.

{"Tanis", "Merlin", Sterling", "Craven"};

Above example in Unity

--

--

Imran Momin
Imran Momin

Written by Imran Momin

A VR/AR developer, who enjoys making games and developing interactive environments using Unity’s XR integration toolkit for Oculus quest and HTC vive devices.

No responses yet