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
MediumMake each click add a box to a list.
- Add
using System.Collections.Generic;and the fieldList<GameObject> boxes = new List<GameObject>();. - On a click, spawn
boxPrefabattransform.position + new Vector3(boxes.Count * 1.5f, 0, 0), with no rotation, and add it toboxes. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch11Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsTake Back the NewestDestroyRandom SpawnsRecap: Fireworks6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground