←All patterns
Game Programming

Runtime Sets

Keep a live list of scene objects in a ScriptableObject that the objects maintain themselves, so nobody has to search the scene.

What Is It?

A runtime set is a ScriptableObject that wraps a List<T>. Objects add themselves in OnEnable and remove themselves in OnDisable. Anything that needs “all the enemies” references the set asset and reads Items, without knowing who spawned them or where they live.

The generic base class RuntimeSet<T> holds the list and the Add/Remove methods. A one-line subclass such as EnemyRuntimeSet : RuntimeSet<Enemy> exists only so Unity can create an asset from it with [CreateAssetMenu], since it cannot serialize a reference to an open generic type.

The trick is that the bookkeeping is tied to Unity’s own lifecycle. Destroying an enemy, disabling it, returning it to a pool or unloading its scene all call OnDisable, so the set is always correct. The minimap, the “enemies left” counter and the wave manager just read it.

When Is It Used?

Use it whenever several systems need the current collection of some kind of object: enemies for a minimap, interactables for a highlight system, spawn points, lights for a day/night cycle, units for a selection box.

It is the natural replacement for FindObjectsOfType, FindObjectsByType and FindGameObjectsWithTag in Update. Those walk the scene and allocate a new array every call; the set is already built.

Skip it when one owner already holds the list (a spawner that never shares it), or when you need spatial queries such as “enemies within 10 m”. A set gives you everything, not what is near; pair it with a spatial partition for that.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Runtime Sets Pattern
in set0scanned/frame0GC alloc0.0 KB
Scene
No enemies. Press Spawn().
Minimap
reads the set
Enemies left 0
EnemyRuntimeSet.asset
RuntimeSet<Enemy>
Items[0]
set.Items0 scanned
FindObjectsOfType48 scanned
Tap an enemy to destroy it · frames: 0 · alloc per frame: 0 B
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ RuntimeSets ›Enemy.cs
using UnityEngine;

namespace Patterns.GameProgramming.RuntimeSets
{
    /// <summary>
    /// Registers itself while active. Pooled, disabled or destroyed enemies
    /// leave the set automatically through OnDisable.
    /// </summary>
    public class Enemy : MonoBehaviour
    {
        [SerializeField] private EnemyRuntimeSet set;
        [SerializeField] private int maxHealth = 30;

        private int health;

        private void OnEnable()
        {
            health = maxHealth;
            set.Add(this);
        }

        private void OnDisable()
        {
            set.Remove(this);
        }

        public void TakeDamage(int amount)
        {
            health -= amount;
            if (health <= 0)
                Destroy(gameObject); // OnDisable runs first, so the set stays correct.
        }
    }
}
4 files · namespace Patterns.Game Programming.RuntimeSetsC# · UTF-8 · LF

Before & After

Real-world smell: a minimap that searches for tagged enemies every frame. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Minimap.Update calls GameObject.FindGameObjectsWithTag("Enemy") on every frame to place its blips and update the counter. It is the first thing many developers write, and with ten enemies it looks fine.

The call walks all tagged objects in every loaded scene and allocates a fresh GameObject[] each time, which shows up as steady GC pressure in the Profiler. It also depends on a string tag: an enemy prefab without the tag is invisible to the minimap, and a renamed tag fails silently.

✓ What changed

  • The minimap gets an EnemyRuntimeSet enemies field and reads enemies.Items instead of calling FindGameObjectsWithTag.
  • No array is allocated per frame; the set is maintained by each Enemy in its OnEnable and OnDisable.
  • The "Enemy" string tag is no longer part of the contract; membership is a typed reference to the set asset.
  • The work moves to LateUpdate, so blips use positions after every enemy has moved this frame.
Minimap.Before.cs → Minimap.After.cs+8/−7
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.RuntimeSets
44 {
55 /// <summary>
6− /// Without a runtime set: every frame the minimap asks the scene for
7− /// everything tagged "Enemy".
6+ /// With a runtime set: enemies register themselves, the minimap just
7+ /// reads the list they maintain.
88 /// </summary>
99 public class Minimap : MonoBehaviour
1010 {
11+ [SerializeField] private EnemyRuntimeSet enemies;
1112 [SerializeField] private RectTransform[] blips;
1213 [SerializeField] private TMPro.TMP_Text enemiesLeft;
1314 [SerializeField] private float worldToMap = 2f;
1415
15− private void Update()
16+ private void LateUpdate()
1617 {
17− // Searches the scene and allocates a new array, every frame.
18− GameObject[] items = GameObject.FindGameObjectsWithTag("Enemy");
18+ // No search, no allocation: the set is already up to date.
19+ var items = enemies.Items;
1920
2021 for (int i = 0; i < blips.Length; i++)
2122 {
22− bool used = i < items.Length;
23+ bool used = i < items.Count;
2324 blips[i].gameObject.SetActive(used);
2425 if (!used) continue;
2526
2627 Vector3 p = items[i].transform.position;
2728 blips[i].anchoredPosition = new Vector2(p.x, p.z) * worldToMap;
2829 }
2930
30− enemiesLeft.SetText("Enemies left: {0}", items.Length);
31+ enemiesLeft.SetText("Enemies left: {0}", items.Count);
3132 }
3233 }
3334 }

Advantages & Disadvantages

+ Advantages

  • No scene searches, no tags and no per-frame allocation to get the current list.
  • Readers are decoupled from spawners; the minimap works whether enemies come from a spawner, a pool or were placed by hand.
  • Membership follows the Unity lifecycle, so pooled or destroyed objects leave the set automatically.

− Disadvantages

  • The list lives on an asset, so in the editor it can keep stale entries between Play sessions unless you clear it.
  • Iterating the set while an item removes itself (for example killing enemies in a foreach) throws InvalidOperationException.
  • Order is registration order, not anything meaningful; sort or partition it yourself if order matters.

Tips

  1. 01Clear the list in the set’s own OnEnable and also when entering Play Mode, so editor sessions never start with leftovers.
  2. 02When you need to destroy items while iterating, loop backwards with a for index or copy the list first.
  3. 03Expose Items as IReadOnlyList<T> so readers cannot add or remove behind the owners’ backs.
  4. 04Add ItemAdded/ItemRemoved events if readers want to react to changes instead of reading the list each frame.
  5. 05Keep Add idempotent (check Contains) because OnEnable can run more than once for the same object.