Skip to content

soraphis/BasicEventBus

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 = EventBinding<TestEvent>.Subscribe(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());

            _onTestEvent.Dispose();
        }
  1. Observation Lifecycle
        private void Awake()
        {
            _onTestEvent = EventBinding<TestEvent>.Subscribe(OnEvent);
        }

        private void OnDisable()
        {
            _onTestEvent.Pause();
        }

        private void OnEnable()
        {
            _onTestEvent.Resume();
        }

        private void OnDestroy()
        {
            _onTestEvent.Dispose();
        }
  1. Using Assembly Definitions

once in your custom assembly mark the assembly, such that it can be cleaned up properly in the Editor even without Domain reload

[assembly: EventBus.EventBusAssembly()]

About

Basic event bus for unity

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 100.0%