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

Managing Event Registration Lifecycles

Ensure memory safety by correctly registering and unregistering listeners during the OnEnable and OnDisable lifecycle methods of your game objects.

In this lesson, you will learn how to prevent memory leaks and "ghost" errors by properly binding and unbinding your objects to Event Channels during their lifecycle.

The Problem: Lingering Subscriptions

When you use the Observer pattern—such as your ScriptableObject Event Channels—you are creating a "link" between your listener and the event. If a Prefab instance is destroyed but fails to "unsubscribe" from the event, the Event Channel will still hold a reference to that object.

This causes two major issues:

  1. Memory Leaks: The garbage collector cannot clean up the destroyed object because the Event Channel is still "pointing" to it.
  2. NullReferenceExceptions: If the Event Channel fires, it will try to trigger a method on an object that no longer exists in the scene, causing your console to flood with errors.

The Solution: Using OnEnable and OnDisable

To ensure memory safety, you must treat your event registration like a contract that is signed when the object wakes up and terminated when it goes away.

We use the OnEnable and OnDisable methods for this. OnEnable runs when the object becomes active, and OnDisable runs when the object is deactivated or destroyed.

public class PlayerHealthUI : MonoBehaviour
{
    [SerializeField] private VoidEventChannel healthChangedChannel;

    private void OnEnable()
    {
        // Subscribe to the event when the object is ready
        healthChangedChannel.OnEventRaised += UpdateUI;
    }

    private void OnDisable()
    {
        // Unsubscribe immediately to prevent memory leaks!
        healthChangedChannel.OnEventRaised -= UpdateUI;
    }

    private void UpdateUI() 
    {
        // Update your UI logic here
    }
}

By following this pattern, you ensure that your Prefab instances are only "listening" while they are active in the game world. If you swap a level or destroy a UI element, the link is broken cleanly, leaving your Event Channel free of stale references and your memory usage stable. Always ensure your subscription logic in OnEnable has a corresponding de-registration in OnDisable.

Key Takeaway: Always pair every subscription in OnEnable with a matching unsubscription in OnDisable to ensure your objects are safely disconnected when they are no longer needed.