←All patterns
Game Programming

Event Queue

Separate the moment a request is sent from the moment it is handled, so bursts are buffered, merged and processed at a steady pace.

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.

Event Queue Pattern
frame1pending0/8merged0dropped0peak voices0
Enemy × 12 · senders
RingBuffer<PlaySoundRequest>[8]
0
1
2
3
4
5
6
7
▲ head
▲ tail
AudioQueue
plays ≤ 2 per frame
voices per frame
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ EventQueue ›Enemy.cs
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);
        }
    }
}
4 files · namespace Patterns.Game Programming.EventQueueC# · UTF-8 · LF

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, hitClip and deathClip fields are gone; the enemy no longer owns any audio setup.
  • TakeDamage and Die call AudioQueue.Instance.Enqueue(new PlaySoundRequest(...)) and return at once.
  • The AudioQueue merges requests with the same SoundId and plays at most maxPerFrame per frame, so twelve deaths become one well-mixed sound.
Enemy.Before.cs → Enemy.After.cs+5/−11
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.EventQueue
44 {
55 /// <summary>
6− /// Without an event queue: every enemy plays its own sounds the moment
7− /// something happens to it.
6+ /// With an event queue: the enemy only asks for sounds. The AudioQueue
7+ /// merges duplicates and plays a limited number per frame.
88 /// </summary>
99 public class Enemy : MonoBehaviour
1010 {
1111 [SerializeField] private int health = 30;
1212 [SerializeField] private float corpseTime = 1.5f;
1313
14− // Every enemy prefab carries its own audio setup.
15− [SerializeField] private AudioSource audioSource;
16− [SerializeField] private AudioClip hitClip;
17− [SerializeField] private AudioClip deathClip;
18−
1914 public void TakeDamage(int amount)
2015 {
2116 if (health <= 0) return;
2217
2318 health -= amount;
24− audioSource.PlayOneShot(hitClip, 0.6f);
19+ AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.Hit, 0.6f));
2520
2621 if (health <= 0)
2722 Die();
2823 }
2924
3025 private void Die()
3126 {
32− // A grenade kills 12 enemies in one frame: 12 identical clips start
33− // on the same sample and stack into one loud, phasey spike.
34− audioSource.PlayOneShot(deathClip);
27+ // 12 deaths in one frame are merged into a single queued request.
28+ AudioQueue.Instance.Enqueue(new PlaySoundRequest(SoundId.EnemyDeath));
3529 GetComponent<Collider>().enabled = false;
3630 Destroy(gameObject, corpseTime);
3731 }
3832 }
3933 }

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

  1. 01Put data, not references, in requests. A struct with an enum id and a position survives the sender being destroyed; a GameObject reference does not.
  2. 02Log every dropped request with Debug.LogWarning during development, so a capacity that is too small is noticed early.
  3. 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.
  4. 04For cross-thread work use System.Collections.Concurrent.ConcurrentQueue<T>; a plain ring buffer is single-threaded.
  5. 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.