Can anyone explain (or point me toward a tutorial that does) how to make the “Event Bus” pattern in C#? I’ve only found resources on how to do this in GDScript, and I haven’t been able to figure out the conversion.
You can do it the same way as it’s done in gdscript. You make an autoload and define your signals there. Then you emit them via the autoload:
public partial class EventBus : Node {
[Signal]
public delegate void SomeSignalEventHandler(string someParam);
}
// connect
GetNode<EventBus>("/root/EventBus").SomeSignal += SignalHandler;
// emit
GetNode<EventBus>("/root/EventBus").EmitSignal(EventBus.SignalName.SomeSignal, "param");
Of course you can also use C# events instead. Since you don’t need any node functionality or access to the scene-tree, you can make it a static class with static events.
public static class EventBus {
// You could also use EventHandler with EventArgs to conform to the C# guidelines
public static event Action<string> SomeEvent;
// You need an extra function since events can only be invoked from the defining class
public static void InvokeSomeEvent(string param) => SomeEvent?.Invoke(param);
}
// connect
EventBus.SomeEvent += SomeEventHandler;
// invoke
EventBus.InvokeSomeEvent("param");
If you are using static event you can also just define them in the relevant classes instead of having a separate EventBus class.