While not silver bullets, message buses (or event buses as Lumberyard calls them) can be an effective mechanism for loosen up coupling between systems. KLab Message Buses for Unity provides a simple API for using buses in Unity with low runtime overhead.
Using a message bus basically consists of 3 steps.
- You declare a message bus
- You connect to it (and later disconnect from it)
- You send messages through the bus
The below is a minimal example. (The example uses Unity components for handling connecting and sending, but you can also use message buses in pure C# classes).
using KLab.MessageBuses;
using UnityEngine;
public sealed class MyMessageBus : MessageBus<string> {}
public sealed class Sender : MonoBehaviour
{
private const string Message = "Hello, World!";
private MyMessageBus Bus { get; set; }
private void Start ()
{
Bus = MessageBus.GetBus<MyMessageBus>();
}
private void Update ()
{
Bus.Broadcast(Message);
}
}
public sealed class Receiver : MonoBehaviour
{
private void OnMessage(string message)
{
Debug.Log(message);
}
private void OnEnable()
{
MessageBus
.GetBus<MyMessageBus>()
.Connect(OnMessage);
}
private void OnDisable()
{
MessageBus
.GetBus<MyMessageBus>()
.Disconnect(OnMessage);
}
}
See here for bus types available.
You can set initial capacities of the underlying containers used by a bus by decorating the bus with options.
using KLab.MessageBuses;
[MessageBusOptions(connectionsCapacity : 1024)]
public sealed class MyMessageBus : MessageBus<string> {}
See here.
See here.
If you want to create a non-global message bus,
simply instantiate the message bus class directly
instead of getting the global singleton through MessageBus.GetBus<T>()
.
The library can be imported easily as a Unity package. It doesn't have any dependencies on other packages.
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog and this project adheres to Semantic Versioning.
- Add options for controlling message bus container capacities
- Rename package from
com.klab.messagebuses
tocom.klab.message-buses
- Rename runtime asmdef from
KLab.MessageBuses
toKLab.MessageBuses.Runtime
- Request a new feature on GitHub
- File a bug in GitHub Issues
Copyright (c) KLab Inc.. All rights reserved.
Licensed under the MIT License.