Power Bus is a flexible event bus system designed to streamline your Unity game development. It allows for easy communication between different parts of your game without tight coupling.
You can define an event bus by creating a new instance of the Bus
class.
using Kekser.PowerBus;
public class StringEvent
{
public string Value { get; set; }
}
var bus = new Bus<StringEvent>();
bus.On += e => Debug.Log(e.Value);
bus.Trigger(new StringEvent { Value = "Hello World" });
You can handle events by subscribing to the On
event of the bus.
void HandleEvent(StringEvent e)
{
Debug.Log(e.Value);
}
bus.On += HandleEvent;
You can create a bus by instantiating the Bus
class.
var bus = new Bus<StringEvent>();
bus.Trigger(new StringEvent { Value = "Hello World" });
You can handle events inline by passing a lambda function or a method to the constructor.
var bus = new Bus<StringEvent>(e => Debug.Log(e.Value));
bus.Trigger(new StringEvent { Value = "Hello World" });
// or
void HandleEvent(StringEvent e)
{
Debug.Log(e.Value);
}
var bus = new Bus<StringEvent>(HandleEvent);
bus.Trigger(new StringEvent { Value = "Hello World" });
You can set the initial value of the bus by passing it to the constructor.
Note: The initial value will be only set once when the bus is created.
var bus = new Bus<StringEvent>(new StringEvent { Value = "Hello World" });
You can manage multiple buses using the BusManager
class.
var manager = new BusManager();
var bus = new Bus<StringEvent>(manager: manager);
bus.Trigger(new StringEvent { Value = "Hello World" });
You can trigger an event globally by calling the Trigger
method on the static bus class.
Bus.Trigger<StringEvent>(new StringEvent { Value = "Hello World" });
You can access the bus from a game object.
You can access a bus from any game object.
var bus = gameObject.Bus<StringEvent>();
bus.Trigger(new StringEvent { Value = "Hello World" });
You can access a bus from a game object that only triggers events locally.
var bus = gameObject.LocalBus<StringEvent>();
bus.Trigger(new StringEvent { Value = "Hello World" });
You can dispose of the bus object by calling the Dispose
method.
Note: You should always dispose of the bus when you no longer need it.
bus.Dispose();
Download the latest release and import the package into your Unity project.
You can add this package to your project by adding this git URL in the Package Manager:
https://github.com/DerKekser/unity-power-bus.git?path=Assets/Kekser/PowerBus
This library is under the MIT License.