Basic event bus for unity
- Simple
- Structs for events - no garbage
- Binding based or direct subscription, no interfaces
- High performance
Create new struct, assign IEvent interface
publicstructTestEvent:IEvent{publicstringa;publicfloatb;}EventBus<TestEvent>.Raise(newTestEvent(){b=7,a="Hello"});Check EventBusExample.cs
- Declare an event binding object
publicclassEventBusTest:MonoBehaviour{EventBinding<TestEvent>_onTestEvent;- Initialize it in Awake/Start/Ctor
privatevoidAwake(){_onTestEvent=newEventBinding<TestEvent>(OnEvent);// Add couple more listeners to the same binding _onTestEvent.Add(onEventButPrintTheStringInstead);_onTestEvent.Add(someUnrelatedMethodWithoutArgs);EventBus<TestEvent>.Raise(newTestEvent(){a="Hello"});_onTestEvent.Remove(onEventButPrintTheStringInstead);_onTestEvent.Remove(someUnrelatedMethodWithoutArgs);// Callback will be called precisely once, then droppedEventBus<TestEvent>.AddCallback(SomeRandomMethod);StartCoroutine(CoroutineThatDispatchesEventAfterSomeTime());StartCoroutine(CoroutineThatWaitsForEvent());}- Control observing state through
Listen
privatevoidOnEnable(){_onTestEvent.Listen=true;}privatevoidOnDisable(){_onTestEvent.Listen=false;}