### Install via Package Manager Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Instructions for installing the UnityEventBus package using the Unity Package Manager by providing a git URL. ```bash https://github.com/NullTale/UnityEventBus.git ``` -------------------------------- ### Define Subscriber Class Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Define a subscriber class that implements IListener interfaces to react to specific event types. This example shows reacting to both enum and generic event messages, and providing interfaces for invocation. ```csharp public class SampleListener : Subscriber, IListener, IListener>, IDamageTaker, IHandle ``` -------------------------------- ### Create Simple Listener with Listener Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Define a simple listener class that inherits from Listener to react to string events. This is a concise way to create subscribers for specific event types. ```csharp using UnityEngine; using UnityEventBus; // same as SimpleListener : Subscriber, IListener public class SimpleListener : Listener { public override void React(in string e) { Debug.Log(e); } } ``` -------------------------------- ### Implement MonoBehaviour Listener and Subscribe Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Implement a MonoBehaviour listener that subscribes to the global bus and reacts to string events. Includes OnEnable for subscription and OnDisable for unsubscription. ```csharp using UnityEngine; using UnityEventBus; public class SimpleListener : MonoBehaviour, IListener { private void Start() { // somewhere in code... // send string event to the global bus GlobalBus.Send("String event"); } // subscribe to the global bus private void OnEnable() { GlobalBus.Subscribe(this); } // unsubscribe from the global bus private void OnDisable() { GlobalBus.UnSubscribe(this); } // react to an event public void React(in string e) { Debug.Log(e); } } ``` -------------------------------- ### Configure Event Bus with EventBus Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Derive from EventBus for auto-subscription and priority configuration. If EventBus implements Subscribers interfaces, they will be automatically subscribed. ```csharp public class Unit : EventBus ``` -------------------------------- ### Receive Event with Multiple Data Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Shows how to retrieve multiple data types from an event. ```csharp // get multiple data var (n, f, unit) = e.GetData(); // or if (e.TryGetData(out int n, out float f, out Unit unit)) { // do something with data } ``` -------------------------------- ### Configure Listener Priority and Name with ISubscriberOptions Source: https://context7.com/nulltale/unityeventbus/llms.txt Implement ISubscriberOptions on any listener to control its priority in event dispatch order and assign a name for debugging. This is useful for non-MonoBehaviour listeners. ```csharp using UnityEventBus; public enum AppEvent { Tick } // Non-MonoBehaviour listener with priority and name public class TickHandler : IListener, ISubscriberOptions { public string Name => "TickHandler"; public int Priority => -5; // runs before default-priority listeners public void React(in AppEvent e) { if (e == AppEvent.Tick) UnityEngine.Debug.Log("High-priority tick received."); } public void Register() => GlobalBus.Subscribe(this); public void Unregister() => GlobalBus.UnSubscribe(this); } // Usage var handler = new TickHandler(); handler.Register(); GlobalBus.Send(AppEvent.Tick); // Output: "High-priority tick received." handler.Unregister(); ``` -------------------------------- ### SendRequest with Approval-Based Query Pattern Source: https://context7.com/nulltale/unityeventbus/llms.txt Dispatches an IRequest that propagates through listeners until one calls e.Approve(), stopping delivery and returning true. Use for permission checks, interruption systems, and conditional gate logic. ```csharp using UnityEngine; using UnityEventBus; public enum AbilityRequest { UsePotion, Revive, OpenChest } // Requester asks permission before executing an ability public class AbilitySystem : EventBusBase { public void TryUsePotion() { bool approved = this.SendRequest(AbilityRequest.UsePotion, 1 /* healAmount */); if (approved) Debug.Log("Potion used successfully."); else Debug.Log("Potion could not be used."); } } // Approver grants or denies the request public class PotionInventory : Subscriber, IListener> { private int _potionCount = 3; public void React(in IRequest e) { switch (e.Key) { case AbilityRequest.UsePotion: if (_potionCount > 0) { _potionCount--; e.Approve(); // stops propagation Debug.Log($"Potion consumed. Remaining: {_potionCount}"); } break; } } } ``` -------------------------------- ### Send Event with Multiple Data Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Demonstrates sending an event with multiple data types. ```csharp // send multiple data SendEvent(UnitEvent.Created, 1, 0.2f, this); ``` -------------------------------- ### Create Local Event Bus with EventBusBase Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Derive from EventBusBase to create a local event bus. Events can be sent to this bus using the Send method. ```csharp using UnityEngine; using UnityEventBus; public class Unit : EventBusBase { private void Start() { // send event to this this.Send("String event"); } } ``` -------------------------------- ### Listen to Timeline SignalAsset Events Source: https://context7.com/nulltale/unityeventbus/llms.txt Implement IListener to react to specific SignalAsset references emitted from Timeline. Ensure the listener derives from Subscriber. ```csharp using UnityEngine; using UnityEngine.Timeline; using UnityEventBus; // Listener reacts to specific SignalAsset references emitted from Timeline public class CutsceneTrigger : Subscriber, IListener { [SerializeField] private SignalAsset m_StartCutscene; [SerializeField] private SignalAsset m_EndCutscene; public void React(in SignalAsset signal) { if (signal == m_StartCutscene) { Debug.Log("Cutscene started."); Time.timeScale = 0f; } else if (signal == m_EndCutscene) { Debug.Log("Cutscene ended."); Time.timeScale = 1f; } } } ``` -------------------------------- ### Implement ISubscriberOptions for Listener Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Extend a MonoBehaviour listener to implement ISubscriberOptions, allowing configuration of the listener's debug name and priority for event handling order. ```csharp public class SimpleListener : MonoBehaviour, IListener, ISubscriberOptions { public string Name => name; public int Priority => 1; } ``` -------------------------------- ### Implement Local Event Bus with EventBusBase Source: https://context7.com/nulltale/unityeventbus/llms.txt Inherit from EventBusBase to create local, scoped event buses on GameObjects. Components can subscribe to these local buses instead of the global one. ```csharp using UnityEngine; using UnityEventBus; public enum UnitEvent { Damage, Death } // Unit is its own event bus — children subscribe to it, not the GlobalBus public class Unit : EventBusBase { public int HP = 10; public void TakeDamage(int amount) { HP -= amount; // Broadcast to all subscribers of this local bus this.Send(UnitEvent.Damage); if (HP <= 0) this.Send(UnitEvent.Death); } } // HealthBar subscribes to the parent Unit bus, not the global bus public class HealthBar : Subscriber, IListener { // In Inspector, set SubscribeTo = FirstParent to target the Unit bus public void React(in UnitEvent e) { if (e == UnitEvent.Damage) Debug.Log("Health bar updated."); if (e == UnitEvent.Death) Debug.Log("Unit destroyed!"); } } ``` -------------------------------- ### IListener: Handle Multiple Event Types Source: https://context7.com/nulltale/unityeventbus/llms.txt Implement multiple IListener interfaces to react to different event types within a single class. Ensure to subscribe and unsubscribe manually. ```csharp using UnityEngine; using UnityEventBus; public enum PlayerEvent { Jump, Land, Die } public enum InputEvent { Fire, Reload } // Listener reacts to both PlayerEvent and InputEvent public class PlayerController : MonoBehaviour, IListener, IListener { private void OnEnable() => GlobalBus.Subscribe(this); private void OnDisable() => GlobalBus.UnSubscribe(this); public void React(in PlayerEvent e) { if (e == PlayerEvent.Die) Debug.Log("Player died."); } public void React(in InputEvent e) { if (e == InputEvent.Fire) Debug.Log("Player fired."); } } ``` -------------------------------- ### Implement Non-MonoBehaviour Subscriber Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Implement a subscriber that does not inherit from MonoBehaviour. This class implements ISubscriberOptions for priority and name, listens for GlobalEvent, and provides an interface for invocation. ```csharp public class SampleListenerClass : ISubscriberOptions, IListener, IDamageTaker, IHandle { // react on sent data public void React(in GlobalEvent e) { if (e == GlobalEvent.GameStart) { // do something } } // provide interface for method invocation public void IDamageTaker.Damage(int dmg) { // do something } // subscriber extra options public string Name => name; // name for debugging purposes public int Priority => 1; // execution order related to other subscribed listeners // subscription methods (bus can be any, in example used global bus singleton) public void Subscribe() => GlobalBus.Subscribe(this); public void Unsubscribe() => GlobalBus.Unsubscribe(this); } ``` -------------------------------- ### Create Disposable Lambda Listener with GenericListener Source: https://context7.com/nulltale/unityeventbus/llms.txt Use GenericListener to wrap a System.Action delegate into an IListener without defining a new class. It implements IDisposable for automatic unsubscription. ```csharp using UnityEngine; using UnityEventBus; public class TempListenerExample : MonoBehaviour { private GenericListener _listener; void Start() { // Create and immediately subscribe a lambda listener _listener = new GenericListener( reaction: msg => Debug.Log($"Got: {msg}"), order: 0, name: "TempStringListener" ); _listener.Subscribe(GlobalBus.Instance); GlobalBus.Send("Hello from lambda!"); // Output: "Got: Hello from lambda!" } void OnDestroy() { // Dispose to unsubscribe from all buses automatically _listener?.Dispose(); } } ``` -------------------------------- ### Send Action with SendAction Extension Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Use the SendAction extension method to invoke an interface method on listeners. The target object must implement an IHandle<> interface. ```csharp public class Unit : EventBus { [ContextMenu("Heal Action")] public void Heal() { // send invoke heal action on the IUnitHP interface this.SendAction(hp => hp.Heal(1)); } } ``` ```csharp public interface IUnitHP { void Heal(int val); } // implement IHandle interface to be an action target public class UnitHP : Subscriber, IUnitHP, IHandle { public int HP = 2; public void Heal(int val) { HP += val; } } ``` -------------------------------- ### SendAction with Interface-Based Method Invocation Source: https://context7.com/nulltale/unityeventbus/llms.txt Dispatches a lambda to all subscribers implementing IHandle, enabling direct method calls without tight coupling. Supports optional filtering via a predicate on the subscriber. ```csharp using UnityEngine; using UnityEventBus; public interface IDamageable { void TakeDamage(int amount); void Heal(int amount); } // Subscriber exposes IDamageable interface as a handle target public class CharacterHealth : Subscriber, IDamageable, IHandle // marks it as SendAction target { public int HP = 100; public void TakeDamage(int amount) { HP = Mathf.Max(0, HP - amount); Debug.Log($"HP after damage: {HP}"); } public void Heal(int amount) { HP = Mathf.Min(100, HP + amount); Debug.Log($"HP after heal: {HP}"); } } // Sender: invoke method on all IDamageable subscribers public class DamageDealer : MonoBehaviour { public void DealAreaDamage(int amount) { // Calls TakeDamage on every IHandle subscriber GlobalBus.SendAction(d => d.TakeDamage(amount)); } public void HealOnlySmall(int amount) { // Filtered: only heal subscribers that are small units GlobalBus.SendAction( d => d.Heal(amount), sub => sub is CharacterHealth ch && ch.HP < 30 ); } } ``` -------------------------------- ### SendEvent Keyed Message with Optional Data Payload Source: https://context7.com/nulltale/unityeventbus/llms.txt Dispatches an IEvent message that bundles an enum key with optional typed data. Listeners implement IListener> and use e.Key to branch on event type and e.GetData() / e.TryGetData(out T) to retrieve payloads. ```csharp using UnityEngine; using UnityEventBus; public enum CombatEvent { Hit, Heal, Death } // Sender: unit broadcasts structured events with data public class CombatUnit : EventBusBase { public void ReceiveHit(int damage) => this.SendEvent(CombatEvent.Hit, damage); public void ReceiveHeal(float ratio) => this.SendEvent(CombatEvent.Heal, ratio); public void Die() => this.SendEvent(CombatEvent.Death); // Multiple data values packed together public void ReceiveHitWithSource(int damage, CombatUnit attacker) => this.SendEvent(CombatEvent.Hit, damage, attacker); } // Listener: reacts to structured combat events public class HitFeedback : Subscriber, IListener> { public void React(in IEvent e) { switch (e.Key) { case CombatEvent.Hit: int dmg = e.GetData(); Debug.Log($"Hit for {dmg} damage."); break; case CombatEvent.Heal: if (e.TryGetData(out float ratio)) Debug.Log($"Healed {ratio * 100}%"); break; case CombatEvent.Death: Debug.Log("Unit died."); break; } } } // EventListener shorthand (equivalent to Subscriber + IListener>) public class DeathEffect : EventListener { public override void React(in IEvent e) { if (e.Key == CombatEvent.Death) Debug.Log("Playing death effect."); } } ``` -------------------------------- ### Programmatically Invoke Timeline SignalAsset Source: https://context7.com/nulltale/unityeventbus/llms.txt Invoke a SignalAsset directly from code to send it as a typed message to the GlobalBus. This allows code to trigger Timeline-driven events. ```csharp using UnityEngine; using UnityEngine.Timeline; using UnityEventBus; // Programmatic signal invocation from code public class CutsceneController : MonoBehaviour { [SerializeField] private SignalAsset m_TriggerSignal; public void TriggerSignal() { // Sends the SignalAsset to the GlobalBus as a typed message m_TriggerSignal.Invoke(); } } ``` -------------------------------- ### Auto-Subscribing Local EventBus to GlobalBus Source: https://context7.com/nulltale/unityeventbus/llms.txt Unit bus auto-subscribes to the GlobalBus on enable, propagating all messages it receives upward to global listeners. Configure 'SubscribeTo = Global' and 'Priority = 0' in the Inspector. ```csharp using UnityEngine; using UnityEventBus; public enum UnitEvent { Damage } // Unit bus auto-subscribes to the GlobalBus on enable, // propagating all messages it receives upward to global listeners. public class Unit : EventBus, IListener { // In Inspector: SubscribeTo = Global, Priority = 0 public void React(in UnitEvent e) { Debug.Log("Unit received damage, forwarding to GlobalBus subscribers."); } } // Global listener receives UnitEvent messages propagated by the Unit bus public class GlobalDamageLogger : MonoBehaviour, IListener { void OnEnable() => GlobalBus.Subscribe(this); void OnDisable() => GlobalBus.UnSubscribe(this); public void React(in UnitEvent e) => Debug.Log("Global: a unit was damaged."); } ``` -------------------------------- ### ListenerAttribute for Auto-Registration via Assembly Scanning Source: https://context7.com/nulltale/unityeventbus/llms.txt Marks a class or static method for automatic global subscription during GlobalBus initialization when CollectClasses or CollectFunctions is enabled. Eliminates manual instantiation and registration of global-scope listeners. ```csharp using UnityEngine; using UnityEventBus; public enum SystemEvent { SceneLoaded, AppFocus } // Class is automatically instantiated and subscribed to GlobalBus on startup [Listener(Active = true, Order = 0, Name = "SceneTracker")] public class SceneTracker : IListener, ISubscriberOptions { public string Name => "SceneTracker"; public int Priority => 0; public void React(in SystemEvent e) { if (e == SystemEvent.SceneLoaded) Debug.Log("Scene loaded — auto-registered listener reacted."); } } // Static method auto-registered as a listener function public static class GlobalHandlers { [Listener(Active = true, Name = "FocusLogger")] public static void OnFocus(SystemEvent e) { if (e == SystemEvent.AppFocus) Debug.Log("App focused — static listener reacted."); } } // Initialize GlobalBus with class and function collection enabled // (place this in a bootstrap MonoBehaviour Awake) // GlobalBus.Create(collectClasses: true, collectFunctions: true); ``` -------------------------------- ### Send Event with SendEvent Extension Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Use the SendEvent extension method to send messages with optional data. Listeners must implement IListener>. ```csharp using UnityEngine; using UnityEventBus; // unit derived from the EventBus class, he is receives events and propagate them to subscribers public class Unit : EventBusBase { private void Start() { // send creation event without data this.SendEvent(UnitEvent.Created); } [ContextMenu("Damage")] public void DamageSelf() { // send event with int data this.SendEvent(UnitEvent.Damage, 1); } [ContextMenu("Heal")] public void HealSelf() { this.SendEvent(UnitEvent.Heal, 1); } } // unit event keys public enum UnitEvent { Created, Damage, Heal } ``` ```csharp using UnityEngine; using UnityEventBus; // OnEnable will subscribe to the unit and start to listen messages // same as UnitHP : EventListener public class UnitHP : Subscriber, IListener> { public int HP = 2; // reacts to UnitEvents public override void React(in IEvent e) { switch (e.Key) { // event with damage or heal key always containts int data case UnitEvent.Damage: HP -= e.GetData(); break; case UnitEvent.Heal: HP += e.GetData(); break; case UnitEvent.Created: break; } } } ``` -------------------------------- ### Send Events to Global Bus Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Demonstrates sending different types of events to the GlobalBus. Includes sending enum events, generic events with data, actions for specific interfaces, and filtered messages. ```csharp // send enum event to the GlobalBus GlobalBus.Send(GlobalEvent.Activate); // send IEvent with custom data GlobalBus.SendEvent(GlobalEvent.Activate, 1f); // send action to the GlobalBus GlobalBus.SendAction(damageTaker => damageTaker.TakeDamage(1)); // send with filtration GlobalBus.Send(GlobalEvent.Activate, sub => sub is Unit); ``` -------------------------------- ### Subscriber: Automatic Subscription Management Source: https://context7.com/nulltale/unityeventbus/llms.txt Derive from the Subscriber base class for automatic subscription and unsubscription management via OnEnable/OnDisable. Configure subscription targets and execution priority. ```csharp using UnityEngine; using UnityEventBus; public enum UnitEvent { Damage, Heal, Death } // Subscriber auto-subscribes to its first parent EventBus on enable public class UnitHealthBar : Subscriber, IListener { [SerializeField] private int m_Priority = -10; // run early // Priority is shown in the Inspector — lower runs first public void React(in UnitEvent e) { switch (e) { case UnitEvent.Damage: UpdateDisplay(-1); break; case UnitEvent.Heal: UpdateDisplay(+1); break; case UnitEvent.Death: gameObject.SetActive(false); break; } } private void UpdateDisplay(int delta) => Debug.Log($"HP changed by {delta}"); } ``` -------------------------------- ### GlobalBus.Send Raw Typed Message Dispatch Source: https://context7.com/nulltale/unityeventbus/llms.txt Dispatches any value or reference type as a message to all IListener subscribers of the global bus. An optional filter restricts delivery to a subset of listeners. This is the lowest-overhead dispatch path. ```csharp using UnityEngine; using UnityEventBus; public enum WeatherEvent { Rain, Sun, Storm } public class WeatherSystem : MonoBehaviour { void Update() { if (Input.GetKeyDown(KeyCode.R)) { // Broadcast to all IListener subscribers GlobalBus.Send(WeatherEvent.Rain); } if (Input.GetKeyDown(KeyCode.S)) { // Only dispatch to subscribers that are outdoor objects GlobalBus.Send(WeatherEvent.Storm, sub => sub is OutdoorObject); } } } public class OutdoorObject : MonoBehaviour, IListener { void OnEnable() => GlobalBus.Subscribe(this); void OnDisable() => GlobalBus.UnSubscribe(this); public void React(in WeatherEvent e) => Debug.Log($"Outdoor object reacting to: {e}"); } ``` -------------------------------- ### Implement Generic MonoBehaviour Listener with Listener Source: https://context7.com/nulltale/unityeventbus/llms.txt Use Listener as a base class for MonoBehaviour components that need to listen to a single event type. This simplifies implementing the IListener interface. ```csharp using UnityEngine; using UnityEventBus; // Identical to: public class StringLogger : Subscriber, IListener public class StringLogger : Listener { public override void React(in string e) { Debug.Log($"[LOG] {e}"); } } // Listens for two distinct message types public class DualListener : Listener { public override void React(in string e) => Debug.Log($"String: {e}"); public override void React(in int e) => Debug.Log($"Int: {e}"); } ``` -------------------------------- ### GlobalBus: Send Raw Typed Messages Source: https://context7.com/nulltale/unityeventbus/llms.txt Use GlobalBus.Send to broadcast raw enum or class messages to all subscribers. Optionally filter subscribers using a predicate. ```csharp using UnityEngine; using UnityEventBus; // ----- Sender side ----- public class GameManager : MonoBehaviour { public enum GameEvent { Start, Pause, Resume, End } void Start() { // Send a plain enum message to all global subscribers GlobalBus.Send(GameEvent.Start); // Send with a filter — only listeners that are "active" units receive it GlobalBus.Send(GameEvent.Resume, sub => sub is Unit unit && unit.IsActive); } } // ----- Listener side ----- public class UIController : MonoBehaviour, IListener { private void OnEnable() => GlobalBus.Subscribe(this); private void OnDisable() => GlobalBus.UnSubscribe(this); public void React(in GameManager.GameEvent e) { switch (e) { case GameManager.GameEvent.Start: Debug.Log("Game started!"); break; case GameManager.GameEvent.Pause: Debug.Log("Game paused."); break; } } } ``` -------------------------------- ### Approve Heal Request - UnitHP Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Listens for 'Heal' requests and approves them if the unit can be healed. This subscriber implements `IListener>` to receive requests. It extracts the heal amount using `GetData()` and calls `e.Approve()` to signal approval. ```csharp public class UnitHP : Subscriber, IListener> { public int HPMax = 2; public int HP = 2; public void React(in IRequest e) { switch (e.Key) { case UnitEvent.Heal: { // if can heal, approve heal request var heal = e.GetData(); if (heal > 0 && HP < HPMax) { HP += heal; e.Approve(); } } break; } } } ``` -------------------------------- ### SignalEmitter MonoBehaviour for Timeline Signals Source: https://context7.com/nulltale/unityeventbus/llms.txt Use the SignalEmitter MonoBehaviour to emit Timeline signals. It can be configured in the Inspector to emit to Global, Parent, This, or Children. ```csharp // The SignalEmitter MonoBehaviour can also be added to a GameObject // and configured in the Inspector to emit to Global / Parent / This / Children. ``` -------------------------------- ### Send Heal Request - Unit Source: https://github.com/nulltale/unityeventbus/blob/master/README.md Sends a 'HealRequest' with data to other subscribers. Use this when you need a response or approval from another subscriber. The `SendRequest` method returns true if the request was approved. ```csharp public class Unit : EventBus { [ContextMenu("HealRequest ")] public void HealRequest() { if (this.SendRequest(UnitEvent.Heal, 1)) { // request was approved // do something, play animation or implement logic } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.