Basic event bus for unity
- Structs for events - no garbage
- Interface based subscription
- High performance (1 mil events fired per frame at 60 fps on my machine)
Create new struct, assign IEvent
interface
public struct TestEvent : IEvent
{
public string a;
public float b;
}
Slower method (has to do lookup to resolve subscribers)
EventBus.Raise(new TestEvent()
{
b = 7,
a = "Hello"
});
Fast method (directly invoke raise on the generic bus)
EventBus<TestEvent>.Raise(new TestEvent()
{
b = 7,
a = "Hello"
});
- Implement desired interfaces on a class
public class EventBusTest : MonoBehaviour,
IEventReceiver<TestEvent>,
IEventReceiver<OnResourceDrop>
{
- Feed instance of it to
EventBus.Register()
void Start()
{
EventBus.Register(this);
}
private void OnDestroy()
{
EventBus.UnRegister(this);
}
It will automatically subscribe everything, reflection is used only once on application start, after that everything is cached and mapped.