Game Events
When the player picks up a coin, many things should happen: the score goes up, a sound plays, the HUD animates, an achievement counter ticks, the save system marks the game as changed. If the coin calls all of those directly, the coin knows about the audio system, the UI, achievements and saving. Every new feature means editing the coin. Events turn that around: the coin announces "I was collected", and whoever cares listens.
Direct calls vs events
| Direct calls | Events | |
|---|---|---|
| Who knows whom | the sender knows every receiver | the sender knows no receivers |
| Adding a reaction | edit the sender | add a listener anywhere |
| Removing a feature | edit the sender | remove the listener |
| Debugging | easy to follow in the code | harder: "who is listening to this?" |
Events are the right tool when one thing happening should cause several unrelated reactions. For one obvious receiver (a gun spawning its own bullet), a direct call is clearer.
C# events
C# has events built in (the C# Events lesson covers the language feature). A player raises Damaged and Died; the HUD, the audio and the game-flow logic subscribe independently:
using System;
var player = new Player(30);
var hud = new Hud(player);
player.Damaged += amount => Console.WriteLine(quot; audio: play 'hurt' ({amount} dmg)");
player.Died += () => Console.WriteLine(" game: switch to GameOver");
player.TakeDamage(12);
player.TakeDamage(12);
player.TakeDamage(12);
player.TakeDamage(5); // already dead: no events
class Player
{
public int Health { get; private set; }
public event Action<int> Damaged;
public event Action Died;
public Player(int health) => Health = health;
public void TakeDamage(int amount)
{
if (Health <= 0) return;
Health = Math.Max(0, Health - amount);
Console.WriteLine(quot;player health {Health}");
Damaged?.Invoke(amount);
if (Health == 0) Died?.Invoke();
}
}
class Hud
{
public Hud(Player player) =>
player.Damaged += _ => Console.WriteLine(quot; hud: health bar -> {player.Health}");
}player health 18
hud: health bar -> 18
audio: play 'hurt' (12 dmg)
player health 6
hud: health bar -> 6
audio: play 'hurt' (12 dmg)
player health 0
hud: health bar -> 0
audio: play 'hurt' (12 dmg)
game: switch to GameOver
The Player class has no idea that a HUD or audio system exists. You could delete the HUD and the player would still compile.
An event bus
Events on individual objects need the listener to find the object first. For game-wide news ("an enemy died", "a level loaded", "an achievement unlocked"), many games use a central event bus: anyone can publish a typed message, anyone can subscribe to a message type.
using System;
using System.Collections.Generic;
var bus = new EventBus();
int kills = 0;
bus.Subscribe<EnemyKilled>(e => kills++);
bus.Subscribe<EnemyKilled>(e => Console.WriteLine(quot; +{e.Points} points for {e.Enemy}"));
bus.Subscribe<EnemyKilled>(e => { if (kills == 3) bus.Publish(new AchievementUnlocked("Hat Trick")); });
bus.Subscribe<AchievementUnlocked>(a => Console.WriteLine(quot; ACHIEVEMENT: {a.Name}"));
foreach (var enemy in new[] { "slime", "bat", "slime", "golem" })
{
Console.WriteLine(quot;{enemy} dies");
bus.Publish(new EnemyKilled(enemy, enemy == "golem" ? 50 : 10));
}
Console.WriteLine(quot;kills: {kills}");
record EnemyKilled(string Enemy, int Points);
record AchievementUnlocked(string Name);
class EventBus
{
readonly Dictionary<Type, List<Delegate>> handlers = new();
public void Subscribe<T>(Action<T> handler)
{
if (!handlers.TryGetValue(typeof(T), out var list)) handlers[typeof(T)] = list = new();
list.Add(handler);
}
public void Publish<T>(T message)
{
if (handlers.TryGetValue(typeof(T), out var list))
foreach (var h in list.ToArray()) ((Action<T>)h)(message);
}
}slime dies
+10 points for slime
bat dies
+10 points for bat
slime dies
+10 points for slime
ACHIEVEMENT: Hat Trick
golem dies
+50 points for golem
kills: 4
list.ToArray() iterates over a copy, so a handler may subscribe or unsubscribe while the event is being delivered without breaking the loop.
Queued events: handle them later
Immediate events run in the middle of whatever raised them. That causes subtle bugs: an enemy dies during the physics step, a listener destroys it, and the physics loop then touches a destroyed object. A common fix is an event queue: publishing only records the event; the game processes the queue at a known point in the frame.
using System;
using System.Collections.Generic;
var queue = new Queue<string>();
var enemies = new List<string> { "slime", "bat", "golem" };
// physics step: collisions only RECORD what happened
foreach (string enemy in enemies)
if (enemy != "golem") queue.Enqueue(quot;destroy:{enemy}");
Console.WriteLine(quot;after physics: {enemies.Count} enemies, {queue.Count} queued events");
// end of frame: now it's safe to change the list
while (queue.Count > 0)
{
string e = queue.Dequeue();
string name = e.Split(':')[1];
enemies.Remove(name);
Console.WriteLine(quot;handled {e}");
}
Console.WriteLine(quot;enemies left: {string.Join(", ", enemies)}");after physics: 3 enemies, 2 queued events
handled destroy:slime
handled destroy:bat
enemies left: golem
Removing from enemies inside the first foreach would have thrown InvalidOperationException ("Collection was modified"). Engines do the same: Unity's Destroy() takes effect at the end of the frame, and Godot's queue_free() deletes the node when it is safe.
Events in the engines
| Engine | Mechanism |
|---|---|
| Unity | C# event/Action, UnityEvent (wired in the Inspector), ScriptableObject "event channels" for cross-scene messages |
| Godot | signals: signal died, died.emit(), player.died.connect(_on_player_died); the editor's Node panel connects them visually |
| Unreal | delegates: DECLARE_DYNAMIC_MULTICAST_DELEGATE for Blueprint-visible events, plain multicast delegates in C++ |
Pitfalls
- Forgotten unsubscribes. A destroyed UI panel that is still subscribed keeps running (and in Unity may touch destroyed objects). Unsubscribe in
OnDisable/OnDestroy,_exit_treeorEndPlay. - Event spaghetti. If every interaction is an event, nobody can follow the game flow. Use events for broadcast news, direct calls for obvious ownership.
- Order dependence. Don't rely on listeners running in subscription order; if order matters, make it explicit.
Test yourself
When are events a better fit than direct method calls?
- When there is exactly one obvious receiver
- When one occurrence should trigger several unrelated reactions
- When performance is critical
- Never
Why would a game queue events instead of handling them immediately?
- To save memory
- So state changes like destroying objects happen at a safe point in the frame
- Because C# events are slow
- To make them random
What is Godot's built-in event mechanism called?
- Delegates
- Signals
- UnityEvents
- Messages