A Case for Static/Global Events in Game Development
If there’s one thing that I’ve learned during my transition from software engineer to game developer, it’s that traditional anti-patterns are often fair game. Singletons are a prime example of this, being a common staple for Unity developers and even a built-in feature in Godot1.
But I’m not here to make a case for or against Singletons. Instead I want to talk about events and static/global delegates. This is a pattern my former colleagues and I strived to avoid when architecting software.
The two biggest reasons to avoid this pattern were:
- How do you isolate these delegates when creating automated test suites?
- How to track and debug calling points and subscriptions?
But in the case of games, things are a bit trickier. Games are incredibly event oriented and are often far more stateful and less deterministic when compared to more traditional software. Things like a rapid stream of user input, physics calculations, network data, and so on define a constant barrage of information on the system.
The bigger concerns in game development are things like raw performance2, order of operations, and a clear separation of concerns. The latter becomes increasingly important as more and more systems are added and expected to “plug and play” with one another.
This is where relying on static delegates can really offer a powerful benefit. Let’s put aside the traditional reasons for avoiding this pattern for now (debugging and testing)3 and look at some real world scenarios where this approach offers a lot of stability and benefit.
#Example Scenario
Let’s say we’re creating a multiplayer shooter game, where players can damage one another using an assortment of weapons. In the code for our player characters, we have some logic around receiving damage and reducing the damaged player’s health. This code will also check if player’s health has been reduced to 0, meaning the player was downed by their attacker.
Skipping the networking
I’m going to omit additional networking events here and just assume that we just want to handle these events locally for each client.
Outside of this player character code, we also want to…
- Update the attacking player’s stats (score, kills, etc)
- Update the damaged (or downed) player’s stats (score, deaths, etc)
- Determine if a score/kill/death limit has been reached and the current match should end
- If the player was downed, we want to display the event in a kill feed4
- Notify the player causing the damage that damage was dealt via a UI element like a hit marker5
Now here’s where this gets interesting. It’s quite likely that the player stats, the kill feed UI, and the hit marker are entirely different systems from one another.
We could try and gather references to all the relevant things we want to notify, but then our player character code would be responsible for a number of things outside of itself. It’s also possible that some of those components may not even be available because they’ve been destroyed, disabled, or haven’t even been instantiated yet.
Or we could pipe all of these events through a service or singleton, but what if it’s not available (yet)?
The beautiful thing about a static is that it’s always present. This can be its downfall and make this solution more fragile, but I believe that if proper precautions are taken it can actually be less fragile than what I listed above.
#A Code Example in Unity (C#)
Let’s do an example of what we outlined above using Unity, simply because it reads well in an article format like this.
In Unity, we can easily use System.Action with the event and static keywords to create a quick solution to this problem. Here we see a static event delegate that our other services can subscribe to in their OnEnable method and clean up in the corresponding OnDisable method.
Clean up after yourself
With
staticdelegates like this, the clean up portion becomes even more important as these subscriptions will persist across scenes! If you don’t clean these up effectively, you can run the risk of memory leaks and null exceptions.
Let’s start with the PlayerCharacter class that is handling the damage logic. This class will contain our two static event delegates: OnDamaged, which is invoked whenever this character is damaged via their ApplyDamage method, and OnDowned, which is invoked when that damage brings their health to 0.
using System;
using UnityEngine;
public class PlayerCharacter : MonoBehaviour {
/** Event that is called when a player character is damaged. */
public static event Action<PlayerCharacter, PlayerCharacter, float> OnDamaged
= (victim, attacker, damage) => {};
/** Event that is called when a player character's health is reduced to 0. */
public static event Action<PlayerCharacter, PlayerCharacter> OnDowned
= (victim, attacker) => {};
public float Health { get; private set; } = 100f;
/** Applies damage to an instance of a player character. */
public void ApplyDamage(PlayerCharacter attacker, float amount) {
if (Health <= 0) {
return; // already downed
}
// perform any other damage calculations here
Health = Mathf.Max(Health - amount, 0);
OnDamaged(this, attacker, amount);
if (Health <= 0) {
OnDowned(this, attacker);
}
}
}
One thing to note here is the arguments we’re relaying via these delegates. For these global events to work well, it’s important to provide as much relevant information to them as possible. This is because we’ll need to infer the context of the action from an almost “purely functional” standpoint.
You might also be wondering why OnDowned is its own event. We could have every listener check the victim’s health inside of OnDamaged, but then every system that cares about kills would need to know how health works. A dedicated event keeps that knowledge inside of PlayerCharacter where it belongs, and lets each listener subscribe to exactly the moment it cares about.
Now let’s do the KillFeed script.
using UnityEngine;
class KillFeed : MonoBehaviour {
/** Start listening for downed events for all player characters when this component is enabled. */
private void OnEnable() {
PlayerCharacter.OnDowned += AddKillToFeed;
}
/** Stop listening for downed events for all player characters when this component is disabled. */
private void OnDisable() {
PlayerCharacter.OnDowned -= AddKillToFeed;
}
/** Add the "attacker -> victim" message to the kill feed. */
private void AddKillToFeed(PlayerCharacter victim, PlayerCharacter attacker) {
// append the kill feed UI element here
}
}
Obviously I didn’t include the code here for appending the UI element, but you can still probably see that creating that code would be fairly straightforward. If you wanted to include the weapon/mechanism used for the kill, you could easily extend the OnDowned event signature with another argument for the damageCauser.
Moving on to the HitMarker component, you’ll see things don’t look that much different from KillFeed. The only difference is that it cares about every hit, so it listens to OnDamaged instead.
using UnityEngine;
class HitMarker : MonoBehaviour {
/** The player character this hit marker belongs to. */
[SerializeField] private PlayerCharacter owner;
/** Determines if the given player character is the same one this hit marker belongs to. */
private bool IsOwningCharacter(PlayerCharacter character) {
return character == owner;
}
/** Start listening for damage events for all player characters when this component is enabled. */
private void OnEnable() {
PlayerCharacter.OnDamaged += PlayHit;
}
/** Stop listening for damage events for all player characters when this component is disabled. */
private void OnDisable() {
PlayerCharacter.OnDamaged -= PlayHit;
}
/** Triggers the animation and sound(s) for the hit marker. */
private void PlayHit(PlayerCharacter victim, PlayerCharacter attacker, float damage) {
if (IsOwningCharacter(attacker)) {
// play hit marker animation + sounds
}
}
}
The biggest difference here is that the HitMarker is going to exist on a per-player basis. So we only want to play the hit marker animation and sound effect(s) if the event is reported with the associated player as the attacker.
Hopefully these examples alone are enough to see how you could further adopt this pattern in your PlayerStats and GameState classes (GameState would likely listen to OnDowned to track kills and end the match when the limit is reached). The responsibility for each system is nicely encapsulated and could easily be implemented in any order after PlayerCharacter was created, all without having to modify the PlayerCharacter class further.
It also means that each of these components can be toggled on/off for testing, different game modes, via user preferences, you name it.
#Taking the Proper Precautions
I mentioned earlier that static events can be fragile if you aren’t careful. Here’s what I’d keep in mind when using them.
Always unsubscribe. Every += in OnEnable should have a matching -= in OnDisable. A static event holds onto a reference to every subscriber, so a forgotten unsubscribe keeps destroyed objects around and will eventually try to call into one of them.
Watch out for disabled domain reloads. If you’ve turned on Unity’s “Enter Play Mode Options” to get into play mode faster, static fields are no longer reset between play sessions. That includes your events and all of their subscribers. You can reset them yourself from inside of PlayerCharacter:
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void ResetStaticEvents() {
OnDamaged = (victim, attacker, damage) => {};
OnDowned = (victim, attacker) => {};
}
Don’t rely on the order of listeners. Subscribers are called in the order they subscribed, which with OnEnable subscriptions is basically whatever order Unity happens to enable your objects. If one system needs to run before another, that’s a sign they should be talking to each other directly, or that the event needs to be split up.
One bad listener ruins it for everyone. If a subscriber throws an exception, the remaining subscribers won’t get called. Keep your handlers small and boring.
#Closing Thoughts
Static events aren’t a silver bullet, and I still wouldn’t reach for them in a typical web app. But games are a constant stream of things happening that a lot of different systems want to know about. Having one well-known place for those systems to listen, without the thing causing the event needing to know they exist, is a trade-off I think is well worth making.