githubEdit

pen-to-squareRegistering & Unregistering Events

Learn how to subscribe to agent events and manage event subscriptions properly.

Basic Registration

Subscribe to an Event

Use RegisterEvent<T>() to subscribe to a specific event type:

using Glitch9.AIDevKit.Agents;

Agent agent = new Agent(config, settings);

// Register an event handler
var subscription = agent.RegisterEvent<AgentStatusChanged>(evt => 
{
    Debug.Log($"Agent status changed to: {evt.NewStatus}");
});

Unregister an Event

var subscription = agent.RegisterEvent<AgentStatusChanged>(OnStatusChanged);

// Later, when done
subscription.Dispose();

Method 2: Explicit Unregistration

Common Patterns

Single Event Handler

Multiple Event Handlers

Method Reference vs Lambda

Both approaches work:

Method reference is better when you need to unregister later:

Lambda cannot be unregistered unless you keep a reference:

Async Event Handlers

Event handlers can be async:

⚠️ Important: The event dispatcher does not wait for async handlers. If you need sequential processing, manage it within your handler.

Event Handler Lifecycle

Component-based Lifecycle (Unity)

Class-based Lifecycle

Conditional Registration

Register events based on configuration:

Error Handling in Event Handlers

Always handle potential errors in your event handlers:

Event Types as Event Handlers

You can handle all events of a base type:

Best Practices

✅ Do

❌ Don't

Complete Example

Next Steps

Last updated