Menu
CoddyTech

Lists of Objects

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 51 of 67.

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

The Stacker should keep track of the boxes it makes:

  • Keep the boxes in a private List<GameObject> field named boxes.
  • Each click spawns a box with no rotation and adds it to the list. A box goes at the stacker's position plus 1.5 on x for every box already in the list: the first at the stacker, the next 1.5 to its right, and so on.
  • Space takes back the newest box: hide it with SetActive(false) and remove it from the list. With no boxes, Space does nothing.
  • After every change to the list, log Boxes: and the count, for example Boxes: 3.

Press Play, click and press Space, 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, and add it
        // Space: hide the newest box and remove it from the list
        // After each change, log "Boxes: " and the count
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics