Course contentsShow
← Unity Game Development
Lesson 270 of 8284. Prefabs and Data ManagementFree lesson

Passing Data Through Game Events

Extend event channels to carry payload data, enabling systems to transmit information like health values or scores during an event broadcast.

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

  1. The Sender: Any object (like a PlayerHealth script) holds a reference to this IntEventChannel. When health changes, it calls RaiseEvent(currentHealth).
  2. The Listener: Your UIHealthBar component listens to the OnEventRaised action. When the event triggers, the listener automatically receives the int value passed from the sender.
  3. 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.