Lists in Unity for Beginners

Lists are often confused with arrays due of their similarities. But lists offer more functionality compared to arrays. In Unity, lists are more powerful that arrays and are easier to perform data operations on. In this tutorial, we will try to understand what are lists and how to use them in Unity.

What are lists in Unity?

Lists are a fundamental data structure that allows you to store and manage collections of elements. Lists are particularly useful when you want to work with multiple objects of the same type and perform operations on them.

You can use lists in Unity to store various types of data, such as Game objects, integers, strings, or custom classes. Lists provide a range of functions and properties to manipulate and access their elements. We will see them one by one in the later section of this tutorial.

Creating a new list in Unity

To use lists in Unity, you need to import the System.Collections.Generic namespace.

To create a new list, you need to use the keyword list followed by angular brackets <>, which hold the data type of the list. Then you need to instantiate it using the “new” keyword and the constructor of the List<T>() class. Here is an example list of type integers. Unlike arrays, we need not specify the size of the list while creating it.

syntax of list in Unity

Assigning values to the list.

Lists are very flexible when it comes to assigning new values. You can either declare them while initializing or add them whenever you like. Since the size of a list is not fixed, you can add as many as you like.

Here is an example of assigning values during initialization.

List<int> newvalues=new List<int>{4,1,3,7};

You can append the list by using the Add() function. This adds a new element to the list at the end.

newvalues.Add(10);

You can also add an array or a list to another list using AddRange() method. Here is how to do it.

List<int> newvalues=new List<int>{4,1,3,7};
List<int> oldvalues=new List<int>{5,9,2,8};

void Start()
{
        newvalues.AddRange(oldvalues);  // add all the values in the list oldvalues to the list newvalues     
}    

Performing operations on the list

Unity allows various techniques to manipulate, search, sort, and access elements of a list. Here are some common operations on lists in Unity along with code samples.

Accessing Elements in a list

You can access elements in a list using their index, similar to arrays. Here’s an example:

int firstNumber = newvalues[0]; 

Finding the size of a list

You can use the list property called “Count” to find the current length of a list. Here is how:

int listSize= newvalues.Count;

Removing Elements from list

We already saw how to add an element to a list. Unity list also allows you to remove element.

The code below will remove the first item in the list with value 10. It will not throw an error, if there are no elements with value 10.

newvalues.Remove(10);

You can also use RemoveAt() to remove an item at the given index.

Checking if an Element Exists

You can check if an element exists in a list using the Contains() method. The function returns true if the list contains the value or else returns false. Here’s an example of using it.

bool hasthenumber= newvalues.Contains(10);

Sorting Elements

You can sort the elements in an accending order using the Sort() method. Here’s an example:

newvalues.Sort();

Printing or iterating through a list

You can use the for loop or foreach loop to iterate through the list. This is very similar to how we do it with the arrays.

foreach (int item in newvalues)
{
    Debug.Log(item);
}

Clearing the List

You can remove all elements from a list using the Clear() method. This deletes all elements and resets the size of the list to 0. Here’s an example:

newvalues.Clear();

Finding Elements in the list

You can find elements in a list based on specific conditions using methods such as Find(), FindIndex(), or FindAll(). All these methods take in another method that returns true or false. Here is example to find even numbers in the list.

newvalues.Find(Evenum)
bool Evenum(int num)
{
    return num%2==0;
}

Find returns the first item that satisfy the condition, FindIndex returns the index of the returned number and FindAll returns all the numbers in the list that satisfy the condition.

Copying the List

You can copy your list on to a new one using the list constructor in Unity. Here is how to do it.

List<int> copy1 = new List<int>(newvalues); //copies newvalues to copy1

Reversing the List

You can reverse the order of elements in a list using the Reverse() method. Here’s an example:

newvalues.Reverse();

Finding Index of an Element

You can find the index of a specific element in a list using the IndexOf() method. This is different compared to FindIndex(). FindIndex() returns the index of the item based on a condition. IndexOf() returns the index of the given item. Here is how to use it.

Debug.Log(newvalues.IndexOf(4));

Creating a sub list

You can create a sub list, based on a range from the parent list using the GetRange() function. Here is how to do it.

List<int> subList = newvalues.GetRange(1, 3);

The sub list will consist of all the elements from index 1 to 3.

Lists vs Arrays in Unity

Lists in Unity are similar to arrays, but with some key differences. Here’s a comparison between lists and arrays in Unity.

  • Flexibility: Lists offer more flexibility compared to arrays. Arrays have a fixed size once they are created, while lists can dynamically resize themselves as elements are added or removed. This makes lists more convenient to work with.
  • Memory Allocation: Arrays typically have a lower memory overhead compared to lists. Lists internally use an array to store elements and manage resizing, which incurs some additional memory overhead. If memory efficiency is critical in your project, arrays are a better choice.
  • Functionality: Lists provide additional functionality compared to arrays. They offer numerous methods for sorting, searching, inserting, and removing elements, making them more versatile for complex operations. Arrays, on the other hand, have fewer built-in functions and require manual manipulation for similar tasks.
  • Namespace: Arrays in Unity, do not require any additional namespace to be added. But to use lists, we need to include System.Collections.Generic namespace.
  • Speed: Arrays generally offer better performance as arrays offer faster memory access compared to lists. Elements in an array are stored in contiguous memory locations, allowing for efficient sequential access.

Whether to use arrays or lists in your project is totally dependent on your reequipments. The only reason for not using list is memory constraints.

Hope this clears all the aspects of lists in Unity. If you have any other questions, feel free to leave them in the comment box below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading