A minimal message bus for Unity that is easy to use. FakeMessageBus can form the basis of an message bus or command bus.
https://github.com/Danila-Che/FakeMessageBus.git?path=/Assets/FakeMessageBus
- In Unity, open Window → Package Manager.
- Press the + button, choose "Add package from git URL..."
- Enter url above and press Add.
Full code that uses the message bus (any type can be used, such as value types or reference types):
- Declare a message type.
usingSystem;publicclassExampleMessage{ ...}publicstructAthotherExampleMessage{ ...}- Then simply register/unregister an object with callbacks decorated with the
ObserveMessageattribute on the message bus.
The callback method must have only one parameter.
usingFakeMessageBus;usingSystem;publicclassExampleObserver:IDisposable{privateMessageBusm_MessageBus;publicExampleObserver(MessageBusmessageBus){m_MessageBus=messageBus;m_MessageBus.Register(this);}publicvoidDispose(){m_MessageBus.Unregister(this);}[ObserveMessage]publicvoidOn(ExampleMessagemessage){
...}[ObserveMessage]publicvoidOn(AthotherExampleMessagemessage){
...}[ObserveMessage]publicvoidOn(intmessage){
...}[ObserveMessage]publicvoidOn(stringmessage){
...}}- At the end, simply send the message using the
Sendmethod.
usingFakeMessageBus;publicclassExampleMessageHandler{privateMessageBusm_MessageBus;publicOnRaiseMessage(){m_MessageBus.Send(newExampleMessage(42));}}MessageBusProxy encapsulates an message bus using the singleton pattern. It has static methods implementing various registration and unregistration strategies for GameObject.
Other static methods:
Interacts with MessageBusProxy to automatically register and unregister with selected strategy (Single, Object, and Recursive). Register GameObject with the OnEnable callback and uregister GameObject with the OnDisable callback.
MessageBus implements the IMessageBus interface. I use the Reflex framework to inject MessageBus.
usingReflex.Core;usingUnityEngine;publicclassProjectInstaller:MonoBehaviour,IInstaller{publicvoidInstallBindings(ContainerBuilderbuilder){builder.AddSingleton(typeof(MessageBus),typeof(IMessageBus));}}usingFakeMessageBus;usingReflex.Core;publicclassExampleObserver:MonoBehaviour{[Inject]privateIMessageBusm_MessageBus;privatevoidOnEnable(){m_MessageBus.Register(this);}privatevoidOnDisable(){m_MessageBus.Unregister(this);}
...}Register an observer with the MessageBus if the observer has valid callbacks. A callback contains only one parameter. The observer will not be registered callback if it contains zero or greater than one parameter.
InvalidCallbackException
Observer has at least one callback is invalid.
Unregister an observer from MessageBus.
Raises an message with the specified arguments.
messageArgs T
The message args to be sended to all registered observer callback.
Removes all callbacks (observers) from the MessageBus.
Gets the number of registered callback for the specified MessageArgs type.
int The number of registered callback