Skip to content

Gettiz/Unity-Hybrid-Event-Bus

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Unity Hybrid Event Bus

​ A lightweight, type-safe event bus system for Unity that supports both code-based and inspector-based workflows. ​

Features​

  • 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 BaseEventListener to hook up UnityEvents in the editor.
  • Zero Garbage Collection (Runtime): Optimized to avoid allocations during event raising. ​

Usage

Define an Event

​ 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;
}

​​

Managing Multiple Subscriptions

​ 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 Events

​ 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
       });
    }
}

Inspector Workflow (UnityEvents)

​ You can also listen to events directly from the Inspector without writing registration code. ​

  1. 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. ​

Priority System

​ 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));

Inspired by

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors