Menu
CoddyTech

Lists in the Inspector

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 19 of 64.

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 icon

Challenge

Easy

Show Mira and Tom's talk one line at a time.

  1. Declare a [System.Serializable] class Line with public strings speaker and text, and add public List<Line> lines;.
  2. At the start, show lines[0]: its speaker in speakerText, its text in lineText.
  3. Space shows the next line, by lines.Count. After the last, hide box and log Dialogue over; then Space does nothing.

Press Play and read with Space. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
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
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground