In this lesson, you will learn how to use ScriptableObject event channels to broadcast global state changes, allowing your UI to react to gameplay events without ever needing a direct reference to the player or enemy systems.
The Problem: Tight Coupling
When a beginner starts out, they often write code like UIManager.instance.UpdateHealth(player.health). This is "tight coupling." If you delete the player or change the UI, your code breaks. To build scalable systems, we want our UI to be "passive"—it should simply wait for a notification and update itself whenever that signal arrives.
The Solution: The Global Event Channel
By creating a ScriptableObject that acts as a broadcast channel, we decouple the sender (the logic) from the receiver (the UI).
- The Event Channel: Create a
ScriptableObjectthat contains aUnityAction. - The Broadcaster: Any gameplay system (like a
Healthscript) simply callsmyEventChannel.Raise()when something changes. - The Listener: The UI Prefab contains an
EventListenercomponent that registers to that sameScriptableObject.
Here is a simplified look at the ScriptableObject channel:
[CreateAssetMenu]
public class GameStateChannel : ScriptableObject
{
public UnityAction OnStateChanged;
public void Raise() => OnStateChanged?.Invoke();
}
Why this matters for Prefabs
Because the GameStateChannel exists as an asset file in your Project window, your UI Prefabs don't need to be linked to a specific Player instance in the scene. You simply drag the GameStateChannel asset into the "Event" slot on your UI Prefab’s EventListener component.
When the game starts, the UI doesn't care who caused the state change; it only cares that the channel fired. This allows you to swap out your Player Prefab, add new UI elements, or modify game rules without ever touching the code that links them together. Your systems remain modular, clean, and entirely independent.
Key Takeaway: Use ScriptableObject event channels to create a communication layer that allows gameplay systems to broadcast changes without knowing which UI elements are listening, effectively decoupling your logic from your visual presentation.