Unity list

Unity List Collection: A Comprehensive Guide

In this article, we will delve into the Unity ‘list‘ class and explore its functionalities in both Unity and the broader C# ecosystem.

Table of contents

Unity List vs. Array

The major distinction between a list and an array lies in the fact that an array has a fixed number of elements defined at instantiation, whereas a list possesses a dynamic number of elements that adjusts based on additions.

I don’t want to go into too much detail about all the differences, but for more information you can consult this article.

Working with Lists

Lists operate similarly to arrays; you must define the type of elements they will store.

using System.Collections.Generic;
using UnityEngine;

public class ListMono : MonoBehaviour
{
    public List<int> numbers = new List<int>();


    private void CreateList()
    {
        var listNumbers = new List<int>() { 5, 2, 3 };
    }
}
            

List of GameObjects

Using a list with gameObjects in inspector

In Unity, you can add a list of gameObjects, just like arrays, they can contain elements of any type.
What’s more, Unity can serialize lists, guaranteeing seamless integration

Start by creating a monobehaviour with a “List<GameObject>” field like this:

public class MyBehaviour : MonoBehaviour 
{
    public List<GameObject> gameObjects = new List<GameObject>();
}

Then assign your monobehaviour to a gameObject in your scene.

Select it, then lock it via the padlock at the top right of the inspector.
Then select the gameObjects you want to add to your scene or prefab.

You can use the “SHIFT” shortcut for multiple selection, or “CTRL” to add an element to your selection.
Drag and drop your elements into the list field in the inspector.

Unity list inspector

Put GameObjects in a list

To add GameObjects to a list, first retrieve the gameObjects you wish to add and then add them to the list using the “Add” function.

For our example, we’ll use Instantiate on a prefab and store the invoked gameObjects in our list as follows:

	private List<GameObject> _gameObjects = new List<GameObject>();

	public GameObject prefab;

	private void Invoke()
	{
		for (int i = 0; i < 10; i++)
		{
			_gameObjects.Add(Instantiate(prefab));
		}
	}

We can then use our list of gameObjects for other actions.

FAQ

How do I get a list of all GameObjects in Unity?

To get a list of all GameObjects present in the scene, you can use: Object.FindObjectsByType(FindObjectsSortMode.None);

By default, inactive gameObjects are not retrieved.
Add the first parameter “FindObjectsInactive.Include” to retrieve them.

This function returns an array of GameObjects.

How do I get an object from a list in Unity?

To retrieve an object from a list, we can use the “Find” method on the list, which takes a predicate function as parameter to apply a condition.

For example, if you want to retrieve the gameObject with a specific tag: var gameObject = myList.Find(x => x.CompareTag("Player"));

If you want to retrieve all elements matching your condition, you can use “FindAll“.

Looping Through a List

The list inherits from an IEnumerable, allowing iteration with “for,” “foreach,” and other constructs.

using System.Collections.Generic;

private void Loop()
{
    var listNumbers = new List<int>() { 5, 2, 3 };

    for (int i = 0; i < listNumbers.Count; i++)
    {
        var number = listNumbers[i];
    }

    foreach (var number in listNumbers)
    {

    }
    
    // Personally, I use this one only with events
    listNumbers.ForEach((number) => {
        // do something
    });
}
            

List Add

To add an element in a list, the Add function is used.

using System.Collections.Generic;

private void Add()
{
    var listNumbers = new List<int>();
    listNumbers.Add(5);
}
            

List Length / Count

To retrieve the number of elements in a list, the Count property is used.
Read the full article on List Length.

using System.Collections.Generic;

public List<GameObject> gameObjects = new List<GameObject>();

private void Count()
{
    int count = gameObjects.Count;
}
            

List Remove

To remove an element from a list, the Remove function is used.

Read the full article on List Remove.

using System.Collections.Generic;

private void Remove()
{
    var listNumbers = new List<int>() { 5, 2, 3 };

    if (listNumbers.Remove(3))
    {
        // 3 is found and removed from the list
        // listNumbers contains only 5, 2 now
    }
}
            

List RemoveAt

To remove an element by index, the RemoveAt function is used. It is generally faster than removing by element.

using System.Collections.Generic;

private void RemoveAt()
{
    var listNumbers = new List<int>() { 5, 2, 3 };

    listNumbers.RemoveAt(1);
    // listNumbers contains only 5, 3 now
}
            

List Find

To find an element, you can loop through and find the element with a condition or use the Find function.

using System.Collections.Generic;

public List<GameObject> gameObjects = new List<GameObject>();

private GameObject FindByInstanceId(int instanceId)
{
    foreach (var gameObj in gameObjects)
    {
        if (gameObj.GetInstanceID() == instanceId)
        {
            return gameObj;
        }
    }

    return null;
}

private GameObject FindByInstanceIdFind(int instanceId)
{
    return gameObjects.Find(x => x.GetInstanceID() == instanceId);
}
            

List Contains

To check if an element exists, you can loop or use the Contains function.

using System.Collections.Generic;

public List<GameObject> gameObjects = new List<GameObject>();

private bool Contains()
{
    // We are in a MonoBehaviour, checking if the current gameObject is in the list
    return gameObjects.Contains(gameObject);
}
            

List Sort

To sort elements, you can use the Sort method. Without arguments, it sorts in ascending order.

using System.Collections.Generic;

private void Sort()
{
    // Asc sort
    var listNumbers = new List<int>() { 5, 2, 3 };
    listNumbers.Sort();

    // Desc sort
    listNumbers.Sort((a, b) => b.CompareTo(a));
}
            

Note: If you need to perform actions on a list in ascending order and then in descending order, it may be interesting to sort the list and then use Reverse.

You can also sort more complex lists:

using System.Collections.Generic;
using System.Linq;

public List<GameObject> gameObjects = new List<GameObject>();

private void SortGameObjectByName()
{
    // Asc
    gameObjects.Sort((a, b) => a.name.CompareTo(b.name));

    // Desc
    gameObjects.Sort((a, b) => b.name.CompareTo(a.name));
}

// Or use LINQ:
// Asc
gameObjects = gameObjects.OrderBy(x => x.name).ToList();

// Desc
gameObjects = gameObjects.OrderByDescending(x => x.name).ToList();
            

List Clear

To clear a list, use the Clear function.

using System.Collections.Generic;

private void Clear()
{
    // Asc sort
    var listNumbers = new List<int>() { 5, 2, 3 };
    listNumbers.Clear();
}
            

Keys points

  • Use a list when you’re going to perform dynamic insertions/deletions, and use an array more in a consultation case.
  • List integrate seamlessly with Unity
  • Like an array, a list can be use with Linq

 

Thanks for reading ! Happy coding !

Leave a Reply

Your email address will not be published. Required fields are marked *