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.
Code
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.
}
}
}using System.Collections.Generic;
using UnityEngine;
namespace Patterns.GameProgramming.RuntimeSets
{
/// <summary>
/// A ScriptableObject that holds a live list of scene objects.
/// Items add and remove themselves; readers just iterate Items.
/// </summary>
public abstract class RuntimeSet<T> : ScriptableObject
{
private readonly List<T> items = new List<T>();
public IReadOnlyList<T> Items => items;
public int Count => items.Count;
public void Add(T item)
{
if (!items.Contains(item))
items.Add(item);
}
public void Remove(T item)
{
items.Remove(item);
}
// Scene objects die with the scene; never trust a list that
// survived from the previous Play session in the editor.
private void OnEnable() => items.Clear();
}
}using UnityEngine;
namespace Patterns.GameProgramming.RuntimeSets
{
/// <summary>
/// Concrete set for enemies. Unity cannot create an asset from an open
/// generic type, so each element type gets a one-line subclass.
/// </summary>
[CreateAssetMenu(menuName = "Runtime Sets/Enemy Runtime Set")]
public class EnemyRuntimeSet : RuntimeSet<Enemy>
{
}
}using UnityEngine;
namespace Patterns.GameProgramming.RuntimeSets
{
/// <summary>
/// Reader: draws a blip per enemy and shows how many are left.
/// No tags, no FindObjectsOfType, no reference to a spawner.
/// </summary>
public class Minimap : MonoBehaviour
{
[SerializeField] private EnemyRuntimeSet enemies;
[SerializeField] private RectTransform[] blips;
[SerializeField] private TMPro.TMP_Text enemiesLeft;
[SerializeField] private float worldToMap = 2f;
private void LateUpdate()
{
var items = enemies.Items;
for (int i = 0; i < blips.Length; i++)
{
bool used = i < items.Count;
blips[i].gameObject.SetActive(used);
if (!used) continue;
Vector3 p = items[i].transform.position;
blips[i].anchoredPosition = new Vector2(p.x, p.z) * worldToMap;
}
enemiesLeft.SetText("Enemies left: {0}", items.Count);
}
}
}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 enemiesfield and readsenemies.Itemsinstead of callingFindGameObjectsWithTag. - No array is allocated per frame; the set is maintained by each
Enemyin itsOnEnableandOnDisable. - 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.
using UnityEngine;
namespace Patterns.GameProgramming.RuntimeSets
{
/// <summary>
/// Without a runtime set: every frame the minimap asks the scene for
/// everything tagged "Enemy".
/// </summary>
public class Minimap : MonoBehaviour
{
[SerializeField] private RectTransform[] blips;
[SerializeField] private TMPro.TMP_Text enemiesLeft;
[SerializeField] private float worldToMap = 2f;
private void Update()
{
// Searches the scene and allocates a new array, every frame.
GameObject[] items = GameObject.FindGameObjectsWithTag("Enemy");
for (int i = 0; i < blips.Length; i++)
{
bool used = i < items.Length;
blips[i].gameObject.SetActive(used);
if (!used) continue;
Vector3 p = items[i].transform.position;
blips[i].anchoredPosition = new Vector2(p.x, p.z) * worldToMap;
}
enemiesLeft.SetText("Enemies left: {0}", items.Length);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.RuntimeSets
{
/// <summary>
/// With a runtime set: enemies register themselves, the minimap just
/// reads the list they maintain.
/// </summary>
public class Minimap : MonoBehaviour
{
[SerializeField] private EnemyRuntimeSet enemies;
[SerializeField] private RectTransform[] blips;
[SerializeField] private TMPro.TMP_Text enemiesLeft;
[SerializeField] private float worldToMap = 2f;
private void LateUpdate()
{
// No search, no allocation: the set is already up to date.
var items = enemies.Items;
for (int i = 0; i < blips.Length; i++)
{
bool used = i < items.Count;
blips[i].gameObject.SetActive(used);
if (!used) continue;
Vector3 p = items[i].transform.position;
blips[i].anchoredPosition = new Vector2(p.x, p.z) * worldToMap;
}
enemiesLeft.SetText("Enemies left: {0}", items.Count);
}
}
}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) throwsInvalidOperationException. - Order is registration order, not anything meaningful; sort or partition it yourself if order matters.
Tips
- 01Clear the list in the set’s own
OnEnableand also when entering Play Mode, so editor sessions never start with leftovers. - 02When you need to destroy items while iterating, loop backwards with a
forindex or copy the list first. - 03Expose
ItemsasIReadOnlyList<T>so readers cannot add or remove behind the owners’ backs. - 04Add
ItemAdded/ItemRemovedevents if readers want to react to changes instead of reading the list each frame. - 05Keep
Addidempotent (checkContains) becauseOnEnablecan run more than once for the same object.