←All patterns
Behavioral

Observer

Let one object broadcast changes to any number of listeners without knowing who they are.

What Is It?

The Observer pattern defines a one-to-many relationship: a subject keeps a list of observers and notifies all of them when something interesting happens. The subject never references concrete observer types — it just raises an event.

In C#, this maps naturally onto event Action<T> or UnityEvent. Observers subscribe with += and unsubscribe with -=; the subject calls Invoke and moves on.

A classic Unity example is player health: when PlayerHealth changes, the health bar animates, the audio system plays a hurt sound and the game-over screen waits for Died — yet PlayerHealth has zero dependencies on any of them.

When Is It Used?

Use it whenever one change should trigger reactions in several unrelated systems: UI updates, achievements, analytics, sound, VFX, quest progress.

It shines when you want to add or remove reactions without touching the source. A new achievement system can subscribe to Died without editing the player at all.

Avoid it for tight, ordered sequences where one step must happen before the next — event chains are hard to follow and their call order is not something you should rely on.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Observer Pattern
HP100listeners0
PlayerHealth
Subject
event HealthChanged · event Died
HealthUI
not listening
AudioMgr
not listening
GameOver
not listening
☠
Console
Press a button to see what happens…

Code

Assets / Scripts / Behavioral/ Observer ›DamageTester.cs
using UnityEngine;

namespace Patterns.Behavioral.Observer
{
    /// <summary>
    /// Drives the subject for testing. Note that it only talks to
    /// PlayerHealth; the UI and audio react on their own.
    /// </summary>
    public class DamageTester : MonoBehaviour
    {
        [SerializeField] private PlayerHealth player;

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
                player.TakeDamage(10);

            if (Input.GetKeyDown(KeyCode.H))
                player.Heal(10);
        }
    }
}
4 files · namespace Patterns.Behavioral.ObserverC# · UTF-8 · LF

Before & After

Real-world smell: a health component that calls every system directly. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

PlayerHealth holds serialized references to the health bar, the audio source, the game-over screen and the achievement tracker, and calls each of them inside TakeDamage.

Every new reaction (a camera shake, a damage-number popup, analytics) means editing the player again. The class cannot even compile in a test scene without all of those systems, and one missing Inspector reference throws a NullReferenceException in the middle of combat.

✓ What changed

  • The five UI/audio/game-over/achievement fields are gone; PlayerHealth now depends on nothing but itself.
  • TakeDamage raises HealthChanged and Died instead of calling systems by name.
  • Each system subscribes in its own OnEnable and unsubscribes in OnDisable, so adding or removing a reaction never touches the player.
PlayerHealth.Before.cs → PlayerHealth.After.cs+7/−15
1+using System;
12 using UnityEngine;
2−using UnityEngine.UI;
33
44 namespace Patterns.Behavioral.Observer
55 {
66 /// <summary>
7− /// Without Observer: the health component knows about, and calls,
8− /// every system that cares about health.
7+ /// With Observer: the health component only announces what happened.
8+ /// UI, audio, game over and achievements subscribe on their own.
99 /// </summary>
1010 public class PlayerHealth : MonoBehaviour
1111 {
1212 [SerializeField] private int maxHealth = 100;
1313
14− // Every new reaction adds another hard reference here.
15− [SerializeField] private Slider healthBar;
16− [SerializeField] private AudioSource audioSource;
17− [SerializeField] private AudioClip hurtClip;
18− [SerializeField] private GameOverScreen gameOverScreen;
19− [SerializeField] private AchievementTracker achievements;
14+ public event Action<int, int> HealthChanged; // (current, max)
15+ public event Action Died;
2016
2117 private int current;
2218
2319 private void Awake() => current = maxHealth;
2420
2521 public void TakeDamage(int amount)
2622 {
2723 if (current <= 0) return;
2824
2925 current = Mathf.Max(0, current - amount);
3026
31− healthBar.value = (float)current / maxHealth;
32− audioSource.PlayOneShot(hurtClip);
27+ HealthChanged?.Invoke(current, maxHealth);
3328
3429 if (current == 0)
35− {
36− gameOverScreen.Show();
37− achievements.Unlock("first_death");
38− }
30+ Died?.Invoke();
3931 }
4032 }
4133 }

Advantages & Disadvantages

+ Advantages

  • Subjects and observers are loosely coupled; either side can change independently.
  • New behaviour is added by subscribing, not by modifying existing code (Open/Closed).
  • Maps directly onto built-in C# events, so there is almost no boilerplate.

− Disadvantages

  • Forgetting to unsubscribe causes leaks and calls on destroyed objects (MissingReferenceException).
  • Control flow becomes implicit — it is harder to trace “who reacts to this?” in a debugger.
  • Notification order is not guaranteed; observers that depend on each other become fragile.

Tips

  1. 01Pair += in OnEnable with -= in OnDisable. It is the single most important habit with events in Unity.
  2. 02Prefer event Action<T> for code-only wiring and UnityEvent when designers need to hook things up in the Inspector.
  3. 03Use the ?.Invoke() null-conditional so raising an event with no listeners is safe.
  4. 04Pass data in the event (HealthChanged(current, max)) so observers do not need to query back into the subject.
  5. 05For game-wide events, consider a ScriptableObject event channel so scenes and prefabs can communicate without direct references.