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
MediumThe Stacker should keep track of the boxes it makes:
- Keep the boxes in a private
List<GameObject>field namedboxes. - 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 exampleBoxes: 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch9Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsDestroyRandom SpawnsRecap: Fireworks