Ctrl+K

Subscribing and Unsubscribing to Events

This guide covers how to subscribe to and unsubscribe from events in Strawberry's Event System.

Two Ways to Subscribe

1. Global Subscription

Listen to an event regardless of who invoked it.

EventManager.Subscribe<PlayerInputEvent>(OnPlayerInput, priority: 100);

void OnPlayerInput(PlayerInputEvent e)
{
    // Handle the event
    if (e.Action == PlayerActions.Jump)
    {
        // Jump logic
    }
}

Global subscriptions receive events from any object that invokes them.

2. Instance-Specific Subscription

Listen only to events invoked by a specific object.

EventManager.Subscribe<PlayerInputEvent>(playerInputComponent, OnPlayerInput, priority: 100);

This is useful when you only care about events from one particular component (e.g., a specific player's input).

Priority

The priority parameter (int) controls execution order. Lower numbers = higher priority (called first). Default is usually 0 or 100 depending on overload.

Unsubscribing

The Subscribe methods return a SubscriptionToken that you can use to unsubscribe later.

SubscriptionToken token = EventManager.Subscribe<PlayerInputEvent>(OnPlayerInput, 100);

// Later...
EventManager.Unsubscribe(token);

Automatic Cleanup

When the subscribing object (usually a BaseComponent) is destroyed, Strawberry automatically removes all its subscriptions. You generally don't need to worry about memory leaks.

However, if you want to stop listening earlier, always use the token to unsubscribe.

Full Example

public class PlayerController : BaseComponent
{
    private SubscriptionToken inputToken;

    public override void OnStart()
    {
        inputToken = EventManager.Subscribe<PlayerInputEvent>(OnPlayerInput, 50);
    }

    private void OnPlayerInput(PlayerInputEvent e)
    {
        // React to input
    }

    public override void OnDestroy()
    {
        // Manual cleanup (optional but good practice)
        if (inputToken != null)
            EventManager.Unsubscribe(inputToken);
    }
}

Best Practices

  • Prefer instance subscriptions when possible for better performance.
  • Use structs for events to reduce GC pressure.
  • Store SubscriptionToken if you need to unsubscribe manually.
  • Higher priority = called earlier.

See Also: