The Event Bus

In our game, we’ll have multiple systems that need to communicate across the node tree. In other words, we have nodes in different branches of the scene tree that need to send signals to one another.

We’ll have various interactions to manage across different layers:

  1. When the player selects a track to play in the UI layer;

  2. When the Synchronizer reaches a new half-beat;

  3. When the player clicks a HitBeat or HitRoller and scores;

  4. When the HitSpawner has no HitBeats or HitRollers in the queue;

We’ll create each of the elements above in upcoming lessons. I just wanted to give you a sense of the node interactions we need to handle.

To coordinate distant nodes, we’ll use the event bus pattern. In short, it consists of using an auto-loaded node exclusively to emit signals.

We don’t add any variables or methods to the node in question to avoid the pitfalls of using singletons, but we use it to emit global events.

You can find a guide dedicated to it in the design pattern series. I invite you to read it if you haven’t already.

Creating the Events.gd Autoload Script

Create a new GDScript file by right-clicking on the RhythmGame/AutoLoad/ folder in the FileSystem dock and selecting New Script….

Double-click on the newly created file to open it.

We’ll define the global signals’ names here. For now, we’ll add a signal we can use with the Synchronizer, but we’ll return to this singleton as we connect more components.

extends Node

## Emitted every time we move a half-beat forward in a song.
signal beat_incremented(msg)

The parameter msg is short for “message”. It’s a Dictionary that contains information from whatever component we emitted the signal from. Dictionaries are ideal because they hold pairs of keys which we can use to name variables.

The connected function can then search for what it needs from the list of keys in the dictionary. We include the msg parameter to show we should pass a dictionary when emitting this signal.

To add the Events.gd as a singleton, head over to Project > Project Settings… > AutoLoad and open the path to Events.gd. Click the Add button.

You may notice some warnings pop up. This is because we don’t emit the signal anywhere in the Events.gd script. You can safely ignore those.

We can now emit signals found in Events.gd from anywhere in our code.

We’ll go over how to connect these signals to different components as we create them, starting with the HitSpawner in the next lesson.