pointcache / BasicEventBus

Basic event bus for unity

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

BasicEventBus

Basic event bus for unity

  • Simple
  • Structs for events - no garbage
  • Binding based or direct subscription, no interfaces
  • High performance

Create an event

Create new struct, assign IEvent interface

public struct TestEvent : IEvent
{
   public string a;
   public float b;

}

Raising an event

EventBus<TestEvent>.Raise(new TestEvent()
{
    b = 7,
    a = "Hello"
});
                

Usage

Check EventBusExample.cs

  1. Declare an event binding object
public class EventBusTest : MonoBehaviour
{
          EventBinding<TestEvent> _onTestEvent;
  1. Initialize it in Awake/Start/Ctor
        private void Awake()
        {
            _onTestEvent = new EventBinding<TestEvent>(OnEvent);
            // Add couple more listeners to the same binding   
            _onTestEvent.Add(onEventButPrintTheStringInstead);
            _onTestEvent.Add(someUnrelatedMethodWithoutArgs);

            EventBus<TestEvent>.Raise(new TestEvent()
            {
                a = "Hello"
            });
                                              
            _onTestEvent.Remove(onEventButPrintTheStringInstead);
            _onTestEvent.Remove(someUnrelatedMethodWithoutArgs);

            // Callback will be called precisely once, then dropped
            EventBus<TestEvent>.AddCallback(SomeRandomMethod);

            StartCoroutine(CoroutineThatDispatchesEventAfterSomeTime());
            StartCoroutine(CoroutineThatWaitsForEvent());
        }
  1. Control observing state through Listen
        private void OnEnable()
        {
            _onTestEvent.Listen = true;
        }

        private void OnDisable()
        {
            _onTestEvent.Listen = false;
        }

About

Basic event bus for unity

License:The Unlicense


Languages

Language:C# 100.0%