Menu
CoddyTech

Lists of Objects

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 65 of 85.

An array has a fixed length, set when it is made. A spawner does not know in advance how many objects it will make, so it keeps them in a List<T>: C#'s array that grows. It lives in System.Collections.Generic, and T is the type of item it holds. This fountain remembers every coin it makes:

using System.Collections.Generic;
using UnityEngine;

public class CoinFountain : MonoBehaviour
{
    public GameObject coinPrefab;
    List<GameObject> coins = new List<GameObject>();

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject coin = Instantiate(coinPrefab, transform.position, Quaternion.identity);
            coins.Add(coin);
            Debug.Log(coins.Count + " coins");
        }
    }
}

Add puts an item at the end, and Count says how many there are, where an array has Length. Reading works as with an array: coins[0] is the first coin, and foreach (GameObject c in coins) visits them all. coins.Remove(coin) takes that item out and coins.RemoveAt(0) takes out the first; the items after it move down one place.

The list itself has to be created with new. A field written as List<GameObject> coins; holds null, and the first Add stops with a NullReferenceException.

challenge icon

Challenge

Medium

Make each click add a box to a list.

  1. Add using System.Collections.Generic; and the field List<GameObject> boxes = new List<GameObject>();.
  2. On a click, spawn boxPrefab at transform.position + new Vector3(boxes.Count * 1.5f, 0, 0), with no rotation, and add it to boxes.
  3. Log "Boxes: " + boxes.Count.

Press Play and click three times: three boxes stand in a row. Then Check.

Try it yourself

using UnityEngine;

public class BoxStacker : MonoBehaviour
{
    public GameObject boxPrefab;
    // boxes: a private List<GameObject>

    void Update()
    {
        // Click: spawn a box, 1.5 further right for every box in the list, add it, log the count
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground