What Is It?
An Event Queue puts a buffer between senders and a receiver. A sender calls Enqueue(request) and returns immediately; the receiver pulls requests out later, usually a few per frame inside its own Update. The request is plain data, typically a small struct, not a method call.
That is the key difference from Observer and an event bus: those deliver synchronously, so the listener runs inside the sender's call stack, right now. A queue decouples when something is processed, not just who processes it. The receiver chooses the timing, can look at everything that is pending, and can merge or drop requests before doing any work.
The classic game example is audio. A grenade kills twelve enemies in one frame and each one asks for PlaySound(EnemyDeath). Played directly, twelve identical clips start on the same sample and stack into one painful spike. Queued, the AudioQueue sees twelve identical requests, keeps one, and plays at most maxPerFrame sounds per frame. Under the hood this is usually a ring buffer: a fixed array whose head and tail indices wrap around, so nothing is allocated at runtime.
When Is It Used?
Use it when many senders can fire the same kind of request in a short burst and the receiver should smooth, batch or deduplicate them: sounds, VFX spawns, damage numbers, tutorial popups, network messages.
It also helps when the receiver must work on its own schedule or thread: loading requests processed one at a time, achievements unlocked after the current combat frame, or main-thread work posted from a background job.
Avoid it when the sender needs an answer or needs the reaction to happen before its next line runs. A queue makes feedback asynchronous and removes the call stack from the debugger, so for “do this now and tell me the result” a direct call or a synchronous event is simpler.
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.EventQueue
{
/// <summary>
/// A sender. It asks for sounds but never plays them: Enqueue() returns
/// immediately, even when a grenade kills twelve enemies in one frame.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] private int health = 30;
[SerializeField] private float corpseTime = 1.5f;
public void TakeDamage(int amount)
{
if (health <= 0) return;
health -= amount;
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.Hit, 0.6f));
if (health <= 0)
Die();
}
private void Die()
{
// Twelve of these in one frame still become a single queued request.
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.EnemyDeath));
GetComponent<Collider>().enabled = false;
Destroy(gameObject, corpseTime);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// The receiver. Senders call Enqueue() and return at once; the queue is
/// drained in Update with a per-frame budget, so a burst of requests is
/// merged and spread out instead of hitting the mixer in a single frame.
/// </summary>
public class AudioQueue : MonoBehaviour
{
[SerializeField] private AudioSource source;
[SerializeField] private AudioClip[] clips; // indexed by SoundId
[SerializeField, Min(1)] private int capacity = 8;
[SerializeField, Min(1)] private int maxPerFrame = 2;
public static AudioQueue Instance { get; private set; }
private RingBuffer<PlaySoundRequest> pending;
private void Awake()
{
Instance = this;
pending = new RingBuffer<PlaySoundRequest>(capacity);
}
private void OnDestroy()
{
if (Instance == this) Instance = null;
}
public void Enqueue(in PlaySoundRequest request)
{
// Merge: the same sound is already waiting, so keep one entry at the louder volume.
for (int i = 0; i < pending.Count; i++)
{
ref PlaySoundRequest queued = ref pending[i];
if (queued.Id != request.Id) continue;
if (request.Volume > queued.Volume) queued = request;
return;
}
if (!pending.TryEnqueue(request))
Debug.LogWarning($"AudioQueue full ({pending.Capacity}), dropped {request.Id}", this);
}
private void Update()
{
for (int i = 0; i < maxPerFrame && pending.TryDequeue(out PlaySoundRequest request); i++)
source.PlayOneShot(clips[(int)request.Id], request.Volume);
}
}
}namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// Fixed-capacity FIFO backed by an array. The head index wraps around,
/// so enqueue and dequeue are O(1) and nothing is allocated after construction.
/// </summary>
public class RingBuffer<T> where T : struct
{
private readonly T[] items;
private int head; // index of the oldest pending item
private int count;
public RingBuffer(int capacity) => items = new T[capacity];
public int Count => count;
public int Capacity => items.Length;
public bool IsFull => count == items.Length;
/// <summary>Pending item at offset i from the head, by reference so it can be merged in place.</summary>
public ref T this[int i] => ref items[(head + i) % items.Length];
public bool TryEnqueue(in T item)
{
if (IsFull) return false;
int tail = (head + count) % items.Length;
items[tail] = item;
count++;
return true;
}
public bool TryDequeue(out T item)
{
if (count == 0)
{
item = default;
return false;
}
item = items[head];
items[head] = default;
head = (head + 1) % items.Length;
count--;
return true;
}
}
}namespace Patterns.GameProgramming.EventQueue
{
public enum SoundId
{
Hit,
EnemyDeath,
CoinPickup,
}
/// <summary>
/// One queued message. A small struct with plain data, so enqueuing it
/// never allocates and never keeps a destroyed GameObject alive.
/// </summary>
public readonly struct PlaySoundRequest
{
public readonly SoundId Id;
public readonly float Volume;
public PlaySoundRequest(SoundId id, float volume = 1f)
{
Id = id;
Volume = volume;
}
}
}Before & After
Real-world smell: enemies that each play their own death sound on the spot. Here is the code without the pattern, the refactored version, and the exact diff between them.
! What’s wrong with it?
Every Enemy prefab carries an AudioSource and two clips, and calls audioSource.PlayOneShot directly inside TakeDamage and Die.
That works for one enemy. When a grenade kills twelve in the same frame, twelve identical deathClips start on the same sample: the mix clips, the sound gets loud and phasey, and there is no single place to limit or merge them.
✓ What changed
- The
audioSource,hitClipanddeathClipfields are gone; the enemy no longer owns any audio setup. TakeDamageandDiecallAudioQueue.Instance.Enqueue(new PlaySoundRequest(...))and return at once.- The
AudioQueuemerges requests with the sameSoundIdand plays at mostmaxPerFrameper frame, so twelve deaths become one well-mixed sound.
using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// Without an event queue: every enemy plays its own sounds the moment
/// something happens to it.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] private int health = 30;
[SerializeField] private float corpseTime = 1.5f;
// Every enemy prefab carries its own audio setup.
[SerializeField] private AudioSource audioSource;
[SerializeField] private AudioClip hitClip;
[SerializeField] private AudioClip deathClip;
public void TakeDamage(int amount)
{
if (health <= 0) return;
health -= amount;
audioSource.PlayOneShot(hitClip, 0.6f);
if (health <= 0)
Die();
}
private void Die()
{
// A grenade kills 12 enemies in one frame: 12 identical clips start
// on the same sample and stack into one loud, phasey spike.
audioSource.PlayOneShot(deathClip);
GetComponent<Collider>().enabled = false;
Destroy(gameObject, corpseTime);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.EventQueue
{
/// <summary>
/// With an event queue: the enemy only asks for sounds. The AudioQueue
/// merges duplicates and plays a limited number per frame.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] private int health = 30;
[SerializeField] private float corpseTime = 1.5f;
public void TakeDamage(int amount)
{
if (health <= 0) return;
health -= amount;
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.Hit, 0.6f));
if (health <= 0)
Die();
}
private void Die()
{
// 12 deaths in one frame are merged into a single queued request.
AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.EnemyDeath));
GetComponent<Collider>().enabled = false;
Destroy(gameObject, corpseTime);
}
}
}Advantages & Disadvantages
+ Advantages
- Bursts are flattened: work is spread over frames with a budget instead of spiking a single frame.
- The receiver sees all pending requests, so it can merge duplicates, prioritise, or drop stale ones.
- Senders and receiver are decoupled in time; a sender never waits for, or runs, the receiver's code.
− Disadvantages
- A fixed-size queue can overflow; you must decide whether to drop, overwrite the oldest, or grow.
- Handling is delayed, so the world may have changed by the time a request is processed (the sender might already be destroyed).
- Debugging is harder: the stack trace at processing time no longer shows who sent the request.
Tips
- 01Put data, not references, in requests. A
structwith an enum id and a position survives the sender being destroyed; aGameObjectreference does not. - 02Log every dropped request with
Debug.LogWarningduring development, so a capacity that is too small is noticed early. - 03Guard against feedback loops: if handling a request can enqueue new ones, process only the count that was pending at the start of the frame.
- 04For cross-thread work use
System.Collections.Concurrent.ConcurrentQueue<T>; a plain ring buffer is single-threaded. - 05Inside the receiver, merge by key (sound id, target) and keep the strongest value, e.g. the loudest volume, so the merged request still feels right.