#4 Implementing An Event Bus in Godot

The nightmare of every developer: null pointers, dangling references, objects that no longer exist… endless bugs and crashes, regardless of whether you’re using Godot, Unity, Unreal, or any other development environment (well, maybe with some exceptions like Rust, of course).

When I started developing Impious, I had a clear objective: “Minimize object references, simplify the code, and avoid unnecessary dependencies between elements.”

Admittedly, it’s much easier and faster to make direct calls when you’re prototyping something quickly. But in a project of reasonable complexity and size, you need to be cautious. So, I tried to avoid such direct calls and references. However, mental fatigue sometimes gets the better of you, and it’s easy to slip into inconsistency when writing code (depending on the day, things might communicate differently).

I wasn’t facing a major issue with this, but as the project grew, reference-related problems began to emerge. Since the game isn’t static and generates dynamically as the player progresses, maintaining direct references with objects that are created and destroyed during runtime is a recipe for disaster.

I lacked a CONSISTENT way for objects to communicate with each other, so during the refactoring process, I decided to implement a robust event system: an Event Bus.

With this singleton, and in just 50 lines of code, I centralized much of the game’s functionality, significantly reducing unexpected bugs and crashes.

Objects don’t need to know that others exist, and that’s a huge advantage.

  • Objects subscribe to events without knowing who emits them, but they receive the necessary data.
  • Objects emit events without knowing who’s subscribed to them, but they send the required information.

This is incredibly useful, especially when you need to make significant changes to the architecture or add new features. If something needs to emit or receive a signal, it won’t interfere much with the existing code, and that’s a big relief.

Of course, this approach has its downsides. It can be cumbersome and requires careful planning. Debugging is also challenging because it’s not easy to track every signal. That’s why custom tools to visualize connections—who’s connected to what and who emits what—are highly recommended.

In my case, I created a very simple panel that updates with the current events and their subscribers. I intended to make something more complete and user-friendly, but for now, I haven’t really needed it. With good search tools, I can easily find who subscribes to what.

That’s it for now. I just wanted to write a quick post about this topic.
Please check out the project on Steam and add it to your wishlist if you’re interested!

Thanks for reading, and see you next time!
Onward!

Similar Posts