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

Implementing Event Listeners As MonoBehaviours

Build a generic listener component that subscribes to an event channel and triggers specific game logic when the event is invoked.

In this lesson, you will learn how to bridge your ScriptableObject Event Channels and your game objects by creating a reusable GameEventListener component.

The Problem: Connecting Data to Logic

Previously, we created ScriptableObject Event Channels to decouple our systems. While these channels allow objects to "shout" messages into the void, we need a way for our GameObjects (like an enemy or a UI panel) to "hear" those messages. If every object had to manually subscribe and unsubscribe from these assets in their own custom scripts, our code would quickly become bloated with repetitive boilerplate.

The Solution: The Generic Listener

Instead, we build a dedicated GameEventListener MonoBehaviour. This script acts as a bridge. It holds a reference to an Event Channel and a UnityEvent that triggers when that channel is invoked. By making this component a MonoBehaviour, we can attach it to any Prefab in our scene and assign the desired response directly in the Inspector.

public class GameEventListener : MonoBehaviour
{
    [SerializeField] private GameEvent eventChannel; // Your SO Asset
    [SerializeField] private UnityEvent response;    // What happens when triggered

    private void OnEnable() => eventChannel.RegisterListener(this);
    private void OnDisable() => eventChannel.UnregisterListener(this);

    public void OnEventRaised()
    {
        response.Invoke();
    }
}

How it Works

  1. Assignment: You drag your Event Channel (the ScriptableObject asset) into the Event Channel slot of the component.
  2. Configuration: In the UnityEvent section, you drag in the specific function you want to call—perhaps a method that plays a sound, triggers an animation, or updates a score.
  3. Execution: When the Event Channel is invoked anywhere in your game, it notifies every GameEventListener registered to it, which in turn fires the linked UnityEvent.

This approach keeps your logic clean. Your game systems don't need to know what listens to them; they only care about sending the message. Meanwhile, your Prefabs stay modular, as you can mix and match listeners without writing new C# classes for every event.

Key Takeaway: Use a dedicated listener MonoBehaviour to bridge your Event Channels and game logic, keeping your systems decoupled and your Inspector workflow highly visual.