Skip to content

Unsubscribing from Events

KennethDevelops edited this page Jul 5, 2023 · 6 revisions

There are a few ways you can unsubscribe from an event with the EventManager:

Unsubscribing a Specific Callback

If you want to stop a specific callback from being called when an event is triggered, you can unsubscribe that particular callback. For example, if you have a method called HandleEnemyDefeated that was subscribed to an EnemyDefeatedHandler event, you can unsubscribe it like so:

EventManager.Unsubscribe<OnEnemyDefeated>(EnemyDefeatedHandler);

Unsubscribing All Callbacks from a Subscriber

If you want to stop all callbacks from a specific subscriber from being called when an event is triggered, you can unsubscribe the subscriber itself. This will remove all callbacks associated with that subscriber. Here's an example:

EventManager.Unsubscribe(this);

The EventManager will automatically unsubscribe any Unity object (MonoBehaviours, Components, etc.) that has been destroyed. This helps avoid undesired behaviours and errors. However, it's still good practice to manage your subscriptions and ensure you unsubscribe when appropriate.

Best Practices for Subscription Management

When working with events, it's generally best to subscribe in the Start or Awake method and unsubscribe in the OnDestroy method. This ensures that your object only listens to events while it's active in the game world. Here's an example:

private void Start() {
    EventManager.Subscribe<OnPlayerHealthChanged>(HandlePlayerHealthChange);
    Debug.Log($"[EventManager] {this.GetType().Name} subscribed to {nameof(OnPlayerHealthChanged)} event.");
}

private void OnDestroy() {
    EventManager.Unsubscribe<OnPlayerHealthChanged>(HandlePlayerHealthChange);
    Debug.Log($"[EventManager] {nameof(HandlePlayerHealthChange)} unsubscribed from {nameof(OnPlayerHealthChanged)} event.");
}

However, there may be times when an object needs to stop listening to an event before it's destroyed, such as when a player character dies or an enemy is defeated. In these cases, it would be appropriate to unsubscribe in the method handling that logic.