A lightweight, type-safe event bus system for Unity that supports both code-based and inspector-based workflows.
- Type-Safe Events: Define events as structs implementing
IEvent. - Priority System: Control execution order with integer priorities.
- Hybrid Workflow:
- Code: Subscribe/Unsubscribe using C# delegates.
- Inspector: Use
BaseEventListenerto hook up UnityEvents in the editor.
- Zero Garbage Collection (Runtime): Optimized to avoid allocations during event raising.
Create a struct that implements IEvent. You can include data fields if needed.
public struct TestEvent : IEvent { }
public struct ShakeCamera : IEvent { }
public struct MoveTransform : IEvent
{
public float liftAmount;
}
Use SubscriptionGroup to manage multiple subscriptions easily.
private SubscriptionGroup subscriptions = new SubscriptionGroup();
private void OnEnable()
{
subscriptions = new SubscriptionGroup();
subscriptions.Add(EventBus<TestEvent>.Subscribe(HandleHighPriorityTestEvent,10));
subscriptions.Add(EventBus<TestEvent>.Subscribe(HandleLowPriorityTestEvent,-10));
}
private void OnDisable()
{
subscriptions.Dispose();
}
Raise an event from anywhere using EventBus<T>.Raise.
public class EventTrigger_Group : MonoBehaviour
{
public void RaiseEvents()
{
EventBus<TestEvent>.Raise(new TestEvent());
EventBus<MoveTransform>.Raise(new MoveTransform
{
liftAmount = objectLiftAmount
});
}
}
You can also listen to events directly from the Inspector without writing registration code.
- Create a class that inherits from
BaseEventListener<T>.
public class TestEventListener : BaseEventListener<TestEvent> { }
2. Add this component to a GameObject.
3. Use the OnEventRaised or OnEventRaisedNoArgs UnityEvents to trigger other scripts.
You can also specify a priority when subscribing. Higher numbers run first.
// Runs first
subscriptions.Add(EventBus<TestEvent>.Subscribe(HandleHighPriorityTestEvent,10));
// Runs last
subscriptions.Add(EventBus<TestEvent>.Subscribe(HandleLowPriorityTestEvent,-10));