Lists in the Inspector
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 16 of 50.
A list of [System.Serializable] entries is a table you fill in the Inspector. This guard walks a route of stops and waits at each one as long as its entry says:
[System.Serializable]
public class Stop
{
public Transform point;
public float wait = 1f;
}
public class Patrol : MonoBehaviour
{
public float speed = 3f;
public List<Stop> stops;
private int current;
private float waited;
void Update()
{
Stop stop = stops[current];
transform.position = Vector3.MoveTowards(transform.position, stop.point.position, speed * Time.deltaTime);
if (transform.position != stop.point.position) return;
waited += Time.deltaTime;
if (waited >= stop.wait)
{
waited = 0f;
current = (current + 1) % stops.Count;
}
}
}The Inspector shows Stops with its count and one foldout per entry, Element 0, Element 1 and so on, each with a Point and a Wait. The + button adds an entry, the minus button removes the selected one, and the handle at the left of a row drags it to a new place in the route. Code reads the list as usual: stops.Count entries, stops[current].point, and (current + 1) % stops.Count goes back to the first stop after the last. A level designer can give one guard three stops and another ten without touching the script.
An array, public Stop[] stops;, shows the same way. Unity's + copies the last entry, so a new stop starts with the same point and wait as the one above it. Unity does not show or save a list of lists, such as List<List<Stop>>, or a Dictionary. Wrap the inner list in a [Serializable] class instead, such as a Route with its own List<Stop>, and keep a list of those.
Challenge
EasyMira and Tom are stuck at a broken bridge. Write the dialogue box in Dialogue.cs, on the HUD. The scene links box, speakerText and lineText, and has the conversation ready for a list named lines.
- Declare a class
Linewith two public strings,speakerandtext, that the Inspector can show, and give Dialogue a publicList<Line>namedlines. - At the start the box shows the first line: its speaker in
speakerTextand its text inlineText. - Each press of Space shows the next line. A conversation can have any number of lines, so go by the list's count.
- Space on the last line hides the box and logs
Dialogue over. After that, Space does nothing.
Press Play, read the conversation with Space, then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class Dialogue : MonoBehaviour
{
public GameObject box;
public TMP_Text speakerText;
public TMP_Text lineText;
void Start()
{
// show the first line
}
void Update()
{
// Space: the next line, or the end of the conversation
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types