In this lesson, you will learn how to expand your ScriptableObject event channels to carry specific data, allowing your game systems to communicate more than just "the event happened."
Moving Beyond Simple Signals
So far, you’ve used ScriptableObject event channels to act as simple "broadcast switches"—one object shouts, and another listens. But what if you need to tell your UI exactly how much health the player has, or inform the ScoreManager exactly how many points to add?
Instead of an event that only triggers a method, we can define our event channel to include a payload. By adding a parameter to your event invocation, you turn a simple signal into a data-carrying package.
Implementing Data Payloads
To implement this, you modify your ScriptableObject event channel to include an Action<T> delegate. This allows your event to broadcast a specific type of data, such as an int, float, or even a custom struct.
Here is how you define a channel that carries a health value:
using UnityEngine;
using UnityEngine.Events;
[CreateAssetMenu]
public class IntEventChannel : ScriptableObject
{
public UnityAction<int> OnEventRaised;
public void RaiseEvent(int value)
{
OnEventRaised?.Invoke(value);
}
}
How It Works
- The Sender: Any object (like a
PlayerHealthscript) holds a reference to thisIntEventChannel. When health changes, it callsRaiseEvent(currentHealth). - The Listener: Your
UIHealthBarcomponent listens to theOnEventRaisedaction. When the event triggers, the listener automatically receives theintvalue passed from the sender. - Decoupling: Because the sender and listener only communicate through this
ScriptableObject, they don't need to know the other exists. The sender doesn't care if a UI bar, an audio system, or a log file is listening; it just sends the data out into the channel.
By embedding data directly into the broadcast, you create a robust, decoupled architecture where systems remain independent while still sharing the critical information needed to keep your game logic synced.
Key Takeaway: Adding parameters to your event channels allows you to transmit specific state information between decoupled systems without creating hard dependencies between them.