Creating a Debugging Interface in Godot (Part 1)

At some point during the development of a game, you need to be able to show information that helps you debug issues in your game. What kind of information? That really depends on your game and what your needs are. It could be as simple as printing some text that shows the result of an internal calculation, or it could be as fancy as a chart showing the ratio of decisions being made by the game’s artificial intelligence.

There are different kinds of debugging needed as well. Sometimes, you need something temporary to help you figure out why that function you just wrote isn’t behaving the way you expect it to. Other times, you want an “official” debugging instrument that lives on as a permanent display in your game’s debugging interface.

How does one go about building a debugging system, however? In this blog tutorial, we’ll build a debugging system in the Godot game engine, one that is flexible, yet powerful. It’s useful both for temporary debugging and a long-term debugging solution. I use this system to provide a debugging interface for my own games, and I want to share how to make one like it in the hopes that it helps you in your own game development efforts.

This will be a multiple-part series. At the end of it, you’ll have the root implementation of the debugging system, and knowledge on how to extend it to suit your debugging purposes.

If you want to see the end result, you can download the sample project from Github: https://github.com/Jantho1990/Sample-Project-Debug-Interface

Existing Debugging Tools in Godot

Godot comes with a number of functionalities that are useful for debugging. The most obvious of these is the trusty print() function. Feed it a string, and that string will get printed out to the debugging console during game runtime. Even when you have a debugging system in place, print() is still useful as part of your toolset for temporary debugging solutions. That said, nothing you show with print() is exposed to an in-game interface, so it’s not very useful if you want to show debugging information on a more permanent basis. Also, if you need to see information that updates on every frame step, the debugging console will quickly be overwhelmed with a flood of printed messages, to the point where Godot will bark at you about printing too many messages. Thus, while print() definitely has its uses, we are still in need of something more robust for long-term debugging solutions.

One way I solved this problem in the past is by creating a DebugLabel node, based on a simple Label. This node would listen for a signal, and when said signal was received it would set its text value to whatever string was sent to it. The code looked something like this:


# DebugLabel
extends Label
export(String) var debug_name = "DebugLabel1"

func _ready() -> void:
  GlobalMessenger.listen(debug_name, self, "on_Debug_message_received")

func _on_Debug_message_received(data):
  text = str(data)

This solution also depended on a separate GlobalMessenger system that functions as a global way of passing information. But that system is a tale for another day.

This gave me a solution for printing debugging information that updated on every process step, without overloading the debugging console. While this little component was useful, it had its drawbacks. Every call to print a message to the DebugLabel would overwrite the previous value, so if I needed to show more than one piece of updating information, I would have to create multiple DebugLabel nodes. It wouldn’t take long for my scenes to be cluttered with DebugLabel nodes. Also, this still wasn’t part of a debugging system. If there was a DebugLabel, it’d show, regardless of whether you needed to view debugging information or not. Thus, while this node also served a valuable purpose, it was not enough for a proper debugging solution.

So what does a debugging solution need? It needs a way to conditionally show and hide debugging information, depending on whether such information needs to be viewed. It also needs to expose a method for game code to interact with it to pass in debugging information. There are many possible kinds of information that we’d want to see, so this interaction method must support being able to accept multiple kinds of information. Finally, there should be an easy way of creating debugging scenes to organize the information in whatever ways make sense to those that view the debugging information.

With that high-level information, let’s start by tackling the first part of that paragraph: conditionally showing and hiding the debugging information.

Creating a Test Scene

But before we start working on the debugging system proper, we should have a test scene that exists to help us test that what we’re creating actually works. It doesn’t need to be anything fancy.

While this part of the tutorial is optional, the tutorial series will be assuming the existence of this test scene. If you choose not to make it, then you’ll have to figure out how to test the debugging system’s code in a different way.

Create a scene, and have it extend Node. Let’s call it “TestScene”. In TestScene, add a Line2D node, make it whatever color you want (I chose red), and set the points to make it some easily-visible size (I set mine to [-25, 0], [25, 0] to make a 50px-long horizontal line). Move the Line2D somewhere near the center of the scene; it doesn’t have to be exact, as long as it isn’t too close to the top or edge of the game window. Finally, click the triangle button to run Godot’s main scene; since we don’t have one defined, Godot will pop up an interface that will allow you to make TestScene the default scene, which you should do.

You can alternatively just run this individual scene without making it the main scene; I have chosen to make it the main scene in this tutorial purely out of convenience.

This is what my version of the test scene looks like after doing these things:

Now that we have a test scene, let’s get to building the debugging system proper.

Creating the DebugLayer Global

We need a way to interact with the debugging interface from anywhere in our game code. The most effective way to do this is to create a global scene that it loaded as part of the AutoLoads. This way, any time our game or a scene in our game is run, the debugging system will always be available.

Start by creating a new scene, called DebugLayer, and have it extend the CanvasLayer node. Once the scene is created, go to the CanvasLayer node properties and set the layer property to 128.

That layer property tells Godot what order it should render CanvasLayer nodes in. The highest value allowed for that property is 128, and since we want debugging information to be rendered atop all other information, that’s what we’ll set our DebugLayer to.

For more information on how CanvasLayer works, you can read this documentation page.

Now, create a script for our node, DebugLayer.gd. For now, we’re not going to add anything to it, we just want the script to be created. Make sure it, as well as the DebugLayer scene, are saved to the directory _debug (which doesn’t exist yet, so you’ll need to create it).

Finally, go to Project -> Project Settings -> AutoLoad, and add the DebugLayer scene (not the DebugLayer.gd script) as an AutoLoad, shortening its name to Debug in the process. This is how we’ll make our debugging interface accessible from all parts of our game.

Yes, you can add scenes to AutoLoad, not just scripts. I actually discovered that thanks to a GDQuest tutorial on their Quest system, and have since used that pattern for a wide variety of purposes, including my debugging system.

To verify that our DebugLayer shows in our game, add a Label child to the DebugLayer scene, then run the game. You should be able to see that Label when you run the game, proving that DebugLayer is being rendered over our TestScene.

Toggle Debug Visibility

This isn’t particularly useful yet, though. We want to control when we show the debugging information. A good way to do this is to designate a key (or combination of keys) that, when pressed, toggles the visibility of DebugLayer and any nodes it contains.

Open up the project settings again, and go to Input Map. In the textbox beside Action:, type “toggle_debug_interface” and press the Add button. Scrolling down to the bottom of the Input Map list will reveal our newly-added action at the bottom.

Now we need to assign some kind of input that will dispatch this toggle_debug_interface action. Clicking the + button will allow you to do this. For this tutorial, I’ve chosen to use Shift + ` as the combination of keys to press (Godot will show ` as QuoteLeft). Once this is done, go ahead and close the project settings window.

It’s time to start adding some code. Let’s go to DebugLayer.gd and add this code:


var show_debug_interface = false


func _ready():
  _set_ui_container_visibility(show_debug_interface)


func _set_ui_container_visibility(boolean):
  visible = boolean

Right away, the editor will show an error on the visible = boolean line. You can confirm the error is valid by running the project and seeing the game crash on that line, with the error The identifier "visible" isn't declared in the current scope. That’s because CanvasLayer doesn’t inherit from the CanvasItem node, so it doesn’t contain a visible property. Therefore, we’ll need to add a node based on Control that acts as a UI container, and it is this node that we’ll toggle visibility for.

CanvasItem is the node all 2D and Control (aka UI) nodes inherit from.

Add a MarginContainer node to DebugLayer, calling it DebugUIContainer. Then, move the test label we created earlier to be a child of the DebugUIContainer. Finally, in DebugLayer.gd, change the visibility target to our new UI container:


onready var _uiContainer = $DebugUIContainer


func _set_ui_container_visibility(boolean):
  _uiContainer.visible = boolean

You may notice that I’m prefixing _uiContainer with an underscore. This is a generally-accepted Godot best practice for identifying class members that are intended to be private, and thus should not be accessed by code outside of that class. I also use camelCase to indicate that this particular variable represents a node. Both are my personal preferences, based on other best practices I’ve observed, and you do not need to adhere to this style of nomenclature for the code to work.

At this point, if you run the test scene, the test label that we’ve added should no longer be visible (because we’ve defaulted visibility to false). That’s only half the battle, of course; we still need to add the actual visibility toggling functionality. Let’s do so now:


func _input(_event):
  if Input.is_action_just_pressed('toggle_debug_interface'):
    show_debug_interface = !show_debug_interface
    _set_ui_container_visibility(show_debug_interface)

_input() is a function Godot runs whenever it detects an input action being dispatched. We’re using it to check if the input action is our toggle_debug_interface action (run in response to our debug key combination we defined earlier). If it is our toggle_debug_interface action, then we invert the value of show_debug_interface and call _set_ui_container_visibility with the new value.

Technically, we could just call the visibility function with the inverted value, but setting a variable exposes to outside code when the debug interface is being shown. While this tutorial is not going to show external code making use of that, it seems a useful enough functionality that we’re going to include it nonetheless.

Run the test scene again, and press Shift + `. This should now reveal our test label within DebugLayer, and prove that we can toggle the debug interface’s visibility. If that’s what happens, congratulations! If not, review the tutorial to try and identify what your implementation did incorrectly.

Congratulations!

We now have the basics of a debugging interface. Namely, we have a DebugLayer scene that will house our debugging information, one that we can make visible or invisible at the press of a couple of keys.

That said, we still don’t have a way of actually adding debugging information. As outlined earlier, we want to be able to implement debugging displays that we can easily reuse, with a simple API for our game code to send debugging information to the debugging system.

To accomplish these objectives, we’ll create something that I call “debug widgets”. How does a debug widget work? Find out in the next part of this tutorial!

You can review the end state of Part 1 in the Github repo by checking out the tutorial-part-1 branch.

Creating a Global Signal System in Godot

If you’ve worked in Godot long enough, you’ll have encountered the signal pattern. This pattern has one part of the code providing signals that it emits, which other parts of the code can listen for and react to. It’s very useful for keeping the parts of your codebase separated by concern, thereby preventing explicit dependencies, while still allowing for communication between different systems. This pattern is commonly used with UI elements, which have no bearing on how the game systems work, but still need to know when certain events happen. With signals, the UI nodes can listen for when specific game events occur, then take the data from those signals and use it to update their visuals.

In Godot, this pattern is implemented through the use of a Node’s signal keyword, emit_signal and connect methods, and a callback function. Example follows:


# Some example node script
extends Node
signal an_awesome_signal

func an_awesome_function():
  emit_signal('an_awesome_signal', 'data that the listeners receive')

func another_awesome_function():
  connect('an_awesome_signal', self, '_on_An_awesome_signal')

func _on_An_awesome_signal(data):
  print(data) # 'data that the listeners receive'

It is considered good Godot practice to name your listener callbacks after the signal they are responding to, prefixed with _on_ and with the first letter of the signal name capitalized.

Of course, you don’t have to just connect to signals within your node. Any node that is in the same scene as another node can connect to that node’s signals and listen for them. As explained, connecting nodes to one another allows for coding systems that need to respond to certain game events, but without having to call externalNode.external_node_method() each time external_node_method needs to be run in response to something happening.

Godot’s signal implementation is great, but there is a caveat: it doesn’t provide a clean way to listen for nodes which exist outside of the current scene. Let’s go back to the UI example. UI nodes and their code are usually kept separate from game systems code (after all, game systems shouldn’t need to manage the UI), often by creating entire scenes which house a portion of some UI widget, like a health bar. But how does said health bar know when it needs to be updated? Given this health bar (let’s call it HealthBarUI) is separate from the systems which actually calculate an entity’s health, we can’t directly connect it to the health system.

One way to solve this problem is to use relative paths when connecting the signals, e.g. ../../../HealthBarUI. Obviously, this solution is very brittle. If you decide that HealthBarUI needs to be moved anywhere in the node tree, you’ll have to update the signal connection path accordingly. It’s not hard to imagine this becoming untenable when adding many nodes which are connected to other nodes outside of their scene tree; it’s a maintenance nightmare.

A better solution would be to create a global singleton which your nodes can connect to, instead, adding it to the global AutoLoads. This alleviates the burden of relative paths by providing a global singleton variable that is guaranteed to be accessible from every scene.

Many programmers will advise against using the Singleton pattern, as creating so-called “god objects” is an easy way to create messy, disorganized code that makes code reuse more difficult. I share this concern, but advocate that there are certain times where you want to have a global singleton, and I consider this one of them. As with all practices and patterns, use your best judgment when it comes to determining how to apply them to solve your systems design problems.

GDQuest gives a good example of this pattern in this article. Basically, for every signal which needs to be globally connected, you add that signal definition to the global singleton, connect your local nodes to the singleton, and call Singleton.emit_signal() whenever you need to emit the global version of that signal. While this pattern works, it obviously gets more complex with each signal that you need to add. It also creates a hard dependency on the singleton, which makes it harder to reuse your nodes in other places without the global singleton.

I would like to propose a different take on the global singleton solution. Instead of explicitly defining global signals inside of a globally-accessible singleton file, we can dynamically add signals and connectors to a GlobalSignal node through add_emitter and add_listener methods. Once a signal is registered, then whenever it is emitted by its node, any registered listeners of that signal will receive it and be able to respond to it, exactly the same as how signals normally work. We avoid a hard dependency on the GlobalSignal singleton because we’re just emitting signals the normal way. It’s a clean solution that takes advantage of how Godot’s signals work as much as possible.

Intrigued? Let me show you how it works.

If you want to skip to the final result, you can access the sample project here: https://github.com/Jantho1990/Godot-Global-Signal.

Also, this post was originally written for Godot 3.x. With Godot 4.0 being (finally) released, I did a quick conversion of the sample project to 4.0 and pushed it up in a separate branch. I won’t update the article with 4.0 versions of code at this time, but there aren’t too many changes, so it shouldn’t be too hard to follow and translate the differences.

Building the Basics

Let’s start by creating the file (I’m assuming you’ll have created a Godot project to work with, first). I’ve called it global_signal.gd. It should extend the basic Node. Once the file is created, we should add it to the global AutoLoads by going into Godot’s project settings, clicking the AutoLoad tab, then adding our script (with the variable name GlobalSignal).

This is how we will make GlobalSignal accessible from any scene’s code. Godot automatically loads any scripts in the AutoLoad section first and places them at the top of the game’s node hierarchy, where they can be accessed by their name.

With that out of the way, let’s start adding code to global_signal.gd. First, we need a way for GlobalSignal to know when a node has a signal that can be emitted globally. Let’s call these nodes emitters. This code should take care of adding emitters for GlobalSignal to keep track of:


# Keeps track of what signal emitters have been registered.
var _emitters = {}


# Register a signal with GlobalSignal, making it accessible to global listeners.
func add_emitter(signal_name: String, emitter: Object) -> void:
  var emitter_data = { 'object': emitter, 'object_id': emitter.get_instance_id() }
  if not _emitters.has(signal_name):
    _emitters[signal_name] = {}
  _emitters[signal_name][emitter.get_instance_id()] = emitter_data

Nothing too complex about this. We create a dictionary to store data for the emitter being added, check to see if we have an existing place to store signals with this name (and create a new dictionary to house them if not), then add it to the _emitters dictionary, storing it by signal name and instance id (the latter being a guaranteed unique key that is already part of the node, something we’ll be taking advantage of later).

We can now register emitters, but we also need a way to register listener nodes. After all, what’s the point of having a global signal if nothing can respond to it? The code for adding listeners is nearly identical to the code for adding emitters; we’re just storing things in a _listeners variable instead of _emitters.


# Keeps track of what listeners have been registered.
var _listeners = {}

# Adds a new global listener.
func add_listener(signal_name: String, listener: Object, method: String) -> void:
  var listener_data = { 'object': listener, 'object_id': listener.get_instance_id(), 'method': method }
  if not _listeners.has(signal_name):
    _listeners[signal_name] = {}
  _listeners[signal_name][listener.get_instance_id()] = listener_data

With that, we now have the ability to add emitters and listeners. What we don’t yet possess is a way to connect these emitters and listeners together. Normally, when using signals, we’d have the listener node connect() to the emitter node, specifying whatever signal it wants to connect to and the callback function which should be invoked (as well as the node where this callback function resides). We need to replicate this functionality here, but how do we ensure that a new emitter gets connected to all current and future listeners, and vice versa?

Simply put, every time we add a new emitter, we need to loop through GlobalSignal‘s listeners, find the ones which want to connect with that emitter’s signal, and perform the connection. The same is true for when we add a new listener: when a new listener is added, we need to loop through the registered emitters, find the ones whose signal matches the one the listener wants to listen to, and perform the connection. To abstract this process, let’s create a couple of functions to take care of this for us.


# Connect an emitter to existing listeners of its signal.
func _connect_emitter_to_listeners(signal_name: String, emitter: Object) -> void:
  var listeners = _listeners[signal_name]
  for listener in listeners.values():
    emitter.connect(signal_name, listener.object, listener.method)


# Connect a listener to emitters who emit the signal it's listening for.
func _connect_listener_to_emitters(signal_name: String, listener: Object, method: String) -> void:
  var emitters = _emitters[signal_name]
  for emitter in emitters.values():
    emitter.object.connect(signal_name, listener, method)

Now we need to modify our existing add functions to run these connector functions.


func add_emitter(signal_name: String, emitter: Object) -> void:
  # ...existing code

  if _listeners.has(signal_name):
    _connect_emitter_to_listeners(signal_name, emitter)


func add_listener(signal_name: String, listener: Object, method: String) -> void:
  # ...existing code

  if _emitters.has(signal_name):
    _connect_listener_to_emitters(signal_name, listener, method)

We first check to make sure an emitter/listener has already been defined before we try to connect to it. Godot doesn’t like it when you try to run code on objects that don’t exist. 😛

With that, the last thing we need to finish the basic implementation is to add a way for removing emitters and listeners when they no longer need to be connected. We can implement such functionality thusly:


# Remove registered emitter and disconnect any listeners connected to it.
func remove_emitter(signal_name: String, emitter: Object) -> void:
  if not _emitters.has(signal_name): return
  if not _emitters[signal_name].has(emitter.get_instance_id()): return  
    
  _emitters[signal_name].erase(emitter.get_instance_id())
    
  if _listeners.has(signal_name):
    for listener in _listeners[signal_name].values():
      if emitter.is_connected(signal_name, listener.object, listener.method):
        emitter.disconnect(signal_name, listener.object, listener.method)


# Remove registered listener and disconnect it from any emitters it was listening to.
func remove_listener(signal_name: String, listener: Object, method: String) -> void:
  if not _listeners.has(signal_name): return
  if not _listeners[signal_name].has(listener.get_instance_id()): return  
    
  _listeners[signal_name].erase(listener.get_instance_id())
    
  if _emitters.has(signal_name):
    for emitter in _emitters[signal_name].values():
      if emitter.object.is_connected(signal_name, listener, method):
        emitter.object.disconnect(signal_name, listener, method)

As with the add functions, the remove functions are both almost identical. We take an emitter (or listener), verify that it exists in our stored collection, and erase it from the collection. After that, we check to see if anything was connected to the thing being removed, and if so we go through all such connections and remove them.

That’s it for the basic implementation! We now have a functional GlobalSignal singleton that we can use to connect emitters and listeners dynamically, whenever we need to.

A Simple Test

Let’s create a simple test to verify that all this is working as intended.

This simple test is included in the sample project.

First, create a Node-based scene in your project. Then, add a LineEdit node and a Label node (along with whatever other Control nodes you want to add to make it appear the way you want), and create the following scripts to attach to them:


# TestLabel
extends Label


func _ready():
  GlobalSignal.add_listener('text_updated', self, '_on_Text_updated')


func _on_Text_updated(text_value: String):
  text = text_value


# TestLineEdit
extends LineEdit

signal text_updated(text_value)


func _ready():
  GlobalSignal.add_emitter('text_updated', self)
  connect('text_changed', self, '_on_Text_changed')


func _on_Text_changed(_value):
  emit_signal('text_updated', text)

You could also use the value argument for _on_Text_changed, instead of taking the direct value of text. It’s a matter of preference.

Assuming you’ve implemented the code from this tutorial correctly, when you run the scene, you should be able to type in the LineEdit node and see the values of the Label node update automatically. If it’s working, congratulations! If not, go back and look through the code samples to see what you might’ve missed, or download the sample project to compare it with yours.

Now, obviously, this is a contrived example. GlobalSignal would be overkill for solving such a simple scenario as the one presented in the test case. Hopefully, though, it illustrates how this approach would be useful for more complex scenarios, such as the HealthBarUI example described earlier. By making our global signal definition dynamic, we avoid having to make updates to GlobalSignal every time we need to add a new globally-accessible signal. We emit signals from the nodes, as you do normally; we just added a way for that signal to be listened to by nodes outside of the node’s scene tree. It’s powerful, flexible, and clean.

Resolving Edge Cases and Bugs

There are some hidden issues that we need to address, however. Let’s take a look at them and see how we can fix them.

Dealing with Destroyed Nodes

Let’s ask ourselves a hypothetical question: what would happen if a registered emitter or listener is destroyed? Say the node is freed by the parent (or the parent itself is freed). Would GlobalSignal know this node no longer exists? The answer is no, it wouldn’t. Subsequently, what would happen if we’re looping through our registered emitters/listeners and we try to access the destroyed node? Godot gets unhappy with us, and crashes.

How do we fix this? There are two approaches we could take:

  • We could poll our dictionaries of registered emitters and listeners every so often (say, once a second) to check and see if there’s any dead nodes, and remove any we find.
  • Alternatively, we could run that same check and destroy whenever we make a call to a function which needs to loop through the lists of emitters and listeners.

Of those two options, I prefer the latter. By only running the check when we explicitly need to loop through our emitters and listeners, we avoid needlessly running the check and thereby introducing additional processing time when we don’t know that it’s necessary (which is what would happen if we went with polling). Thus, we’re going to implement this only-when-necessary check in the four places that need it: namely, whenever we add or remove an emitter or listener.

There is an argument to be made that running the check as part of adding/removing emitters/listeners adds additional processing time when performing these functions. That’s true, but in practice I’ve found that the added time isn’t noticeable. That said, if your game is constantly creating and destroying nodes that need to be globally listened to, and it’s measurably impacting game performance, it may prove better to implement a poll-based solution. I’m just not going to do it as part of this tutorial.

First, let’s create a function that will both perform the check and remove the emitter/listener if it is determined it no longer exists.


# Checks stored listener or emitter data to see if it should be removed from its group, and purges if so.
# Returns true if the listener or emitter was purged, and false if it wasn't.
func _process_purge(data: Dictionary, group: Dictionary) -> bool:
  var object_exists = !!weakref(data.object).get_ref() and is_instance_valid(data.object)
  
  if !object_exists or data.object.get_instance_id() != data.object_id:
    group.erase(data.object_id)
    return true
  return false

First, we check all the possible ways that indicate that a node (or object, which is what a node is based on) no longer exists. weakref() checks to see if the object only exists by reference (aka has been destroyed and is pending removal from memory), and is_instance_valid is a built in Godot method that returns whether Godot thinks the instance no longer exists. I’ve found that I’ve needed both checks to verify whether or not the object truly exists.

You may want to abstract this object existence check into some kind of helper function that is made globally accessible. This is what I’ve done in my own implementation of GlobalSignal, but I chose to include it directly in this tutorial to avoid having to create another file exclusively to house that helper.

Even if we prove the object exists, we still need to check to make sure the stored instance id for the emitter/listener matches the current instance id of said object. If they don’t match, then it means the stored object is no longer the same as the one we registered (aka the reference to it changed).

If the object doesn’t exist, or if it’s not the same object as the one we registered, then we need to remove it from our dictionary. group is the collection we passed in for validation (this will be explained in more detail momentarily), and group.erase(data.object_id) deletes whatever value is stored at the key with the same name as data.object_id. If we’ve reached this point, we then return true. If we didn’t erase the object, we return false.

With our purge function defined, let’s go ahead and modify our add and remove functions to implement it:


func _connect_emitter_to_listeners(signal_name: String, emitter: Object) -> void:
  var listeners = _listeners[signal_name]
  for listener in listeners.values():
    if _process_purge(listener, listeners):
      continue
    emitter.connect(signal_name, listener.object, listener.method)


func _connect_listener_to_emitters(signal_name: String, listener: Object, method: String) -> void:
  var emitters = _emitters[signal_name]
  for emitter in emitters.values():
    if _process_purge(emitter, emitters):
      continue
    emitter.object.connect(signal_name, listener, method)


func remove_emitter(signal_name: String, emitter: Object) -> void:
  # ...existing code
    
  if _listeners.has(signal_name):
    for listener in _listeners[signal_name].values():
      if _process_purge(listener, _listeners[signal_name]):
        continue
      if emitter.is_connected(signal_name, listener.object, listener.method):
        emitter.disconnect(signal_name, listener.object, listener.method)


func remove_listener(signal_name: String, listener: Object, method: String) -> void:
  # ...existing code
    
  if _emitters.has(signal_name):
    for emitter in _emitters[signal_name].values():
      if _process_purge(emitter, _emitters[signal_name]):
        continue
      if emitter.object.is_connected(signal_name, listener, method):
        emitter.object.disconnect(signal_name, listener, method)

For each function, the only thing we’ve changed is adding the _process_purge() check before doing anything else with the emitters/listeners. Let’s examine what’s happening in _connect_emitter_to_listeners(), to detail the logic.

As we start looping through our dictionary of listeners (grouped by signal_name), we first call _process_purge(listener, listeners) in an if statement. From examining the code, listener is the current listener node (aka the object we want to verify exists) and listeners is the group of listeners for a particular signal_name. If _process_purge() returns true, that means the listener did not exist, so we continue to move on to the next stored listener. If _process_purge() returns false, then the listener does exist, and we can proceed with connecting the emitter to the listener.

The same thing happens for the other three functions, just with different values passed into _process_purge(), so I shan’t dissect them further. Hopefully, the examination of what happens in _connect_emitter_to_listeners() should make it clear how things work.

That’s one issue down. Let’s move on to the last issue that needs to be addressed before we can declare GlobalSignal complete.

Accessing an Emitter/Listener Before It’s Ready

Here’s another scenario to consider: what happens if we want to emit a globally-accessible signal during the _ready() call? You can try this out yourself by adding this line of code to TestLineEdit.gd, right after defining the global signal:


GlobalSignal.add_emitter('text_updated', self)
emit_signal('text_updated', 'text in _ready()')

We’d expect that, on starting our scene, our Label node should have the text set to “text in _ready()”. In practice, however, nothing happens. Why, though? We’ve established that we can use GlobalSignal to listen for nodes, so why doesn’t the connection in Label seem to be working?

To answer this question, let’s talk a little about Godot’s initialization process. When a scene is added to a scene tree (whether that be the root scene tree or a parent’s scene tree), the _ready() function is called on the lowermost child nodes, followed by the _ready() functions of the parents of those children, and so on and so forth. For sibling children (aka child nodes sharing the same parent), Godot calls them in tree order; in other words, Child 1 runs before Child 2. In our scene tree composition for the sample project, the LineEdit node comes before the Label node, which means the _ready() function in LineEdit runs first. Since Label is registering the global listener in its _ready() function, and that function is running after LineEdit‘s _ready() function, our text_updated signal gets emitted before the listener in Label is registered. In other words, the signal is being emitted too early.

How do we fix this? In our contrived example, we could move the Label to appear before the LineEdit, but then that changes where the two nodes are being rendered. Besides, basing things on _ready() order isn’t ideal. In the case where we want nodes in different scenes to listen for their signals, we can hardly keep track of when those nodes run their _ready() function, at least not without some complex mapping of your scene hierarchy that is painful to maintain.

The best to solve this problem is to provide some way to guarantee that, when emit_signal is called, that both the emitter and any listeners of it are ready to go. We’ll do this by adding a function called emit_signal_when_ready() which we call whenever we need to emit a signal and guarantee that any listeners for it that have been defined in _ready() functions are registered.

Unfortunately, we can’t override the existing emit_signal function itself to do this, because emit_signal uses variadic arguments (aka the ability to define any number of arguments to the function), which is something Godot does not allow for user-created functions. Therefore, we need to create a separate function for this.

We’ll need to add more than just the emit_signal_when_ready() function itself to make this functionality work, so I’ll go ahead and show all of the code which needs to be added, and then cover what’s going on in detail.


# Queue used for signals emitted with emit_signal_when_ready.
var _emit_queue = []

# Is false until after _ready() has been run.
var _gs_ready = false


# We only run this once, to process the _emit_queue. We disable processing afterwards.
func _process(_delta):
  if not _gs_ready:
    _make_ready()
    set_process(false)
    set_physics_process(false)


# Execute the ready process and initiate processing the emit queue.
func _make_ready() -> void:
  _gs_ready = true
  _process_emit_queue()


# Emits any queued signal emissions, then clears the emit queue.
func _process_emit_queue() -> void:
  for emitted_signal in _emit_queue:
    emitted_signal.args.push_front(emitted_signal.signal_name)
    emitted_signal.emitter.callv('emit_signal', emitted_signal.args)
  _emit_queue = []


# A variant of emit_signal that defers emitting the signal until the first physics process step.
# Useful when you want to emit a global signal during a _ready function and guarantee the emitter and listener are ready.
func emit_signal_when_ready(signal_name: String, args: Array, emitter: Object) -> void:
  if not _emitters.has(signal_name):
    push_error('GlobalSignal.emit_signal_when_ready: Signal is not registered with GlobalSignal (' + signal_name + ').')
    return
  
  if not _gs_ready:
    _emit_queue.push_back({ 'signal_name': signal_name, 'args': args, 'emitter': emitter })
  else:
    # GlobalSignal is ready, so just call emit_signal with the provided args.
    args.push_front(signal_name)
    emitter.callv('emit_signal', args)

That’s quite a lot to take in, so let’s break it down, starting with the two class members being added, _emit_queue and _gs_ready.

_emit_queue is a simple array that we’re going to use to keep track of any signals that have been marked as needing to be emitted when GlobalSignal decides everything is ready to go. _gs_ready is a variable that will be used to communicate when GlobalSignal considers everything ready.

I use _gs_ready instead of _ready to avoid giving a variable the same name as a class function. While I’ve found that Godot does allow you to do that, I consider it bad practice to have variables with the same name as functions; it’s confusing, and confusing code is hard to understand.

Next, let’s examine our call to _process() (a built-in Godot process that runs on every frame update):


# We only run this once, to process the _emit_queue. We disable processing afterwards.
func _process(_delta):
  if not _gs_ready:
    _make_ready()
    set_process(false)
    set_physics_process(false)

If _gs_ready is false (which is what we’ve defaulted it to), then we call _make_ready() and subsequently disable the process and physics process update steps. Since GlobalSignal doesn’t need to be run on updates, we can save processing time by disabling them once we’ve run _process() the first time. Additionally, since GlobalSignal is an AutoLoad, this _process() will be run shortly after the entire scene tree is loaded and ready to go.

Let’s check out what _make_ready() does:


# Execute the ready process and initiate processing the emit queue.
func _make_ready() -> void:
  _gs_ready = true
  _process_emit_queue()

The function sets _gs_ready to true, then calls _process_emit_queue(). By marking _gs_ready as true, it signals that GlobalSignal now considers things to be ready to go.

Moving on to _process_emit_queue():


# Emits any queued signal emissions, then clears the emit queue.
func _process_emit_queue() -> void:
  for emitted_signal in _emit_queue:
    emitted_signal.args.push_front(emitted_signal.signal_name)
    emitted_signal.emitter.callv('emit_signal', emitted_signal.args)
  _emit_queue = []

Here, we loop through the _emit_queue array, push the signal name to the front of the arguments array, and use callv to manually call the emit_signal() function on the emitter node, passing in the array of arguments (emit_signal() takes the signal’s name as the first argument, which is why we needed to make the signal name the first member of the arguments array) . When we’ve gone through all of the members of _emit_queue, we reset it to an empty array.

Finally, we come to the emit_signal_when_ready() function, itself:


# A variant of emit_signal that defers emitting the signal until the first process step.
# Useful when you want to emit a global signal during a _ready function and guarantee the emitter and listener are ready.
func emit_signal_when_ready(signal_name: String, args: Array, emitter: Object) -> void:
  if not _emitters.has(signal_name):
    push_error('GlobalSignal.emit_signal_when_ready: Signal is not registered with GlobalSignal (' + signal_name + ').')
    return
  
  if not _gs_ready:
    _emit_queue.push_back({ 'signal_name': signal_name, 'args': args, 'emitter': emitter })
  else:
    # GlobalSignal is ready, so just call emit_signal with the provided args.
    args.push_front(signal_name)
    emitter.callv('emit_signal', args)

First, we check to see if the signal we want to emit has been registered with GlobalSignal, and return early if it is not (with an error pushed to Godot’s console to tell us this scenario happened). Our next action depends on the value of _gs_ready. If it’s false (aka we aren’t ready), then we add a new entry to _emit_queue and pass in the signal name, arguments, and emitter node, all of which will be utilized during _process_emit_queue(). If it’s true, then we called this function after everything has been marked as ready; in that case, there’s no point in adding this to the emit queue, so we’ll just invoke emit_signal() and call it a day.

With that, GlobalSignal should now be able to handle dispatching signals and guaranteeing that the listeners defined during _ready() functions are registered. Let’s test this by changing our modification to TestLineEdit so it uses emit_signal_when_ready():


GlobalSignal.add_emitter('text_updated', self)
GlobalSignal.emit_signal_when_ready('text_updated', ['text in _ready()'], self)

Note that we need to convert our ‘text in _ready()’ argument to be wrapped in an array, since we need to pass an array of arguments to the function.

Also note that we have to pass in the emitter node, since we have to store that in order to call emit_signal() on it later.

If, when you run the scene, the Label node shows our text string, that means our changes worked! Now we can declare GlobalSignal done!

Using Global Signals

Congratulations! You now have a dynamic way to define globally-accessible signals that closely follows Godot’s natural signals implementation. Adding new global signals is easy, and doesn’t involve changing the GlobalSignal singleton at all.

At this point, you might wonder, “Why not convert all of my signals to be global signals?” That’s not necessarily a great idea. Most of the time, we want to keep our signals local, as when we start connecting code from disparate parts of our code base it can make it confusing to recall which things are connected to what. By keeping signals local whenever possible, we make dependencies clearer and make it harder to design bad code.

That’s one of the things I actually like about this approach to implementing global signals. We’re still emitting signals locally; we just choose which signals need to also be exposed globally. You can connect signals locally and globally, with the same signal definitions.

What are some good use cases? UI nodes, as mentioned before, are a great example of a good use case for this pattern. An achievements system needing to know when certain events occur is another possible use case. Generally, this pattern is best suited for when you have multiple “major” systems that need to talk to one another in an agnostic manner, while local signal connections are better for communication between the individual parts of a major system.

As with any pattern or best practice, GlobalSignal should be carefully considered as one of many solutions to your problem, and chosen if it proves to be the best fit.

One last time, here is the link to the sample project, if you didn’t build along with the tutorial, or just want something to compare your implementation against. (And if you are using Godot 4.0, here is the branch with that version of it!)

Hopefully, this approach to global signals helps you in your projects. I’ve certainly made great use of it in mine!

How to Add GDScript Syntax Highlighting to Your Blog

Recently, I decided to devote more time to writing blog posts, especially tutorials about things I’ve learned in my three-plus years of learning Godot and GDScript. When I went to write my first tutorial post, however, I discovered that there is no support for GDScript syntax highlighting in any of the code formatting plugins for WordPress. On top of that, Github’s Gists, which I’ve used to show syntax-highlighted code in the past, also does not support GDScript.

Syntax highlighting, for those who don’t know, is the colorful text and different font weights and decorations (aka bolded, italicized, and underlined text) that code editors show to indicate different functionalities of code. Using syntax highlighting to show what your code is doing is extremely helpful, if not critically important for making your code readable. Without syntax highlighting, it’s a lot more difficult to parse what a given block of code is doing, to the point where it feels unreadable. For tutorials, it’s especially important to make code as easy to understand as possible, and a critical part of that is including syntax highlighting.

Imagine trying to read a blog article where all the code samples were one giant block of monochromatic text, like this:

It’s a little tricky, isn’t it? Maybe you can read this particular example after a few moments, but what about 20-50 line examples of complex code? And what if you’re scanning back and forth between code samples, trying to parse how the whole thing works? It was clear to me that, if I wanted to write tutorials that were user-friendly, I needed to find a way to add support for GDScript syntax highlighting to my website.

After asking in the Godot Discord, I was pointed towards an implementation of GDScript in highlight.js, a JavaScript-based syntax highlighter. Some additional googling showed me how I could integrate highlight.js onto a website, and further research showed how to make changes to a WordPress website’s head file. Combining this information together, I was able to successfully integrate highlight.js and the GDscript extension for it onto my blog.

First, I went to Appearance -> Theme Editor and edited the header.php file, adding this snippet right below the wp_head() function call, to take care of downloading highlight.js:

<!-- Syntax highlighting for code blocks. -->
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>

Next, I went to the Github repo for hilightjs-gdscript and copied the contents of the gdscript.min.js file, adding it just below where I added the main highlight.js script tag:

<!-- Syntax highlighting for GDScript. -->
<script>hljs.registerLanguage("gdscript",function(){"use strict";var e=e||{};function r(e){return{aliases:["godot","gdscript"],keywords:{keyword:"and in not or self void as assert breakpoint class class_name extends is func setget signal tool yield const enum export onready static var break continue if elif else for pass return match while remote sync master puppet remotesync mastersync puppetsync",built_in:"Color8 ColorN abs acos asin atan atan2 bytes2var cartesian2polar ceil char clamp convert cos cosh db2linear decimals dectime deg2rad dict2inst ease exp floor fmod fposmod funcref get_stack hash inst2dict instance_from_id inverse_lerp is_equal_approx is_inf is_instance_valid is_nan is_zero_approx len lerp lerp_angle linear2db load log max min move_toward nearest_po2 ord parse_json polar2cartesian posmod pow preload print_stack push_error push_warning rad2deg rand_range rand_seed randf randi randomize range_lerp round seed sign sin sinh smoothstep sqrt step_decimals stepify str str2var tan tanh to_json type_exists typeof validate_json var2bytes var2str weakref wrapf wrapi bool int float String NodePath Vector2 Rect2 Transform2D Vector3 Rect3 Plane Quat Basis Transform Color RID Object NodePath Dictionary Array PoolByteArray PoolIntArray PoolRealArray PoolStringArray PoolVector2Array PoolVector3Array PoolColorArray",literal:"true false null"},contains:[e.NUMBER_MODE,e.HASH_COMMENT_MODE,{className:"comment",begin:/"""/,end:/"""/},e.QUOTE_STRING_MODE,{variants:[{className:"function",beginKeywords:"func"},{className:"class",beginKeywords:"class"}],end:/:/,contains:[e.UNDERSCORE_TITLE_MODE]}]}}return e.exports=function(e){e.registerLanguage("gdscript",r)},e.exports.definer=r,e.exports.definer||e.exports}());</script>

Imagine trying to read the above without syntax highlighting!

Finally, I added a call to initiate highlight.js, right below the highlightjs-gdscript code:

<script>hljs.highlightAll();</script>

And with that (omitting some trial and error on my part to figure out the above), I successfully got highlight.js to run on my WordPress blog, with syntax highlighting for GDscript!

I wasn’t happy with the out-of-the-box highlighting, though, so I decided to quickly throw together some custom styles, targeting the classes highlight.js injects. First, I went to Appearance -> Edit CSS in the WordPress menu settings and injected this CSS styling:

:root {
    --code-background: #000004;
    --default-font-color: #fbfef9;
    --keyword-color: #7e1946;
    --title-color: #a63446;
    --function-color: #0c6291;
    --string-color: #6ea735;
    --html-color: #a76e35;
}

code {
	border: none;
	padding: 0;
	font-size: 0.9em;
}

pre, code, code.hljs {
    background: var(--code-background);
    color: var(--default-font-color);
}

code.hljs .hljs-function,
code.hljs .hljs-function .hljs-keyword {
    color: var(--function-color);
}

code.hljs .hljs-keyword {
    color: var(--keyword-color);
}

code.hljs .hljs-title {
    color: var(--title-color);
}

code.hljs .hljs-string {
    color: var(--string-color);
}

code.hljs .hljs-name,
code.hljs .hljs-tag,
code.hljs .hljs-attr {
    color: var(--html-color);
}

I also made changes to other parts of the highlight.js syntax highlighting that weren’t for GDScript to make them work with my new color scheme.

I also noticed that highlight.js wasn’t consistently auto-detecting when I was using GDScript, so I converted my WordPress code block to an HTML block and created the code tags manually:

<pre class="wp-block-code"><code class="language-gdscript"></code></pre>

Finally, highlightjs-gdscript didn’t include support for print, so I quickly added that to my import of the dist file:

{ keyword:"and in not or self void as assert breakpoint class class_name extends is func setget signal tool yield const enum export onready static var break continue if elif else for pass return match while remote sync master puppet remotesync mastersync puppetsync print" }

The final result looks like this:

At least, that’s what it looked like at the time I wrote this blog post. Since I was just looking to throw something together quickly, I didn’t put too much thought into my color scheme, instead utilizing a randomly-generated color palette (https://coolors.co/a63446-fbfef9-0c6291-000004-7e1946) and some hue-shifting to get related colors that weren’t part of the generated palette. Below is what the syntax highlight looks like on today’s iteration of the color scheme:

func ready():
  var variable = some_function()
  print("Hopefully this syntax highlighting works!")

Anyway, that’s a quick overview on how I implemented GDScript syntax highlighting on a WordPress blog. I imagine much of this can be adapted to implement GDScript syntax highlighting on any site. Now, on to writing blog posts!

Hammertime Prototype – Phase 1 (Download)

Link to download a simple prototype project. Available for Windows only.

Hammertime Prototype Phase 1

Controls:
AWSD = Move/Jump
Right Mouse = Throw Hammer
Right Mouse (while hammer in air) = Teleport to Hammer's location
Left Mouse (while hammer in air) = Create platform
Left Click (on platform) = Select platform
Left Click (anywhere but a platform) = Deselect selected platform
q (while platform selected) = Delete platform
q (no platform selected) = Delete all platforms

If you need a goal, you can try to collect all the tomes. The main point of this prototype, however, is to play around with the movement mechanics.

Godot Node Selection Square Getting Fixed

In Godot 3.0, when you create a scene or a node, a 64×64 selection square appears around it by default. You cannot change the size of this selection square, and resizing it changes the scale of the scene/node, rather than resizing it.

To get the portal placed on the ground, I have to monkey around with offsets in the instanced scene itself. Ugh.

It gets particularly annoying when you are trying to place said scene/node instead of a snap-grid, and the 64×64 area not only clashes visually with your grid, it makes it hard to determine where the position actually is! It’s been a source of frustration for me as I learn how to make games using Godot.

Sprite is 32×32, but selection square is larger, so I can’t place the start position on the ground. Grr.

The good news it that this seems to be one of the things getting changed for Godot 3.1. While looking to see if there are ways to work around this quirk of Godot, I came across this change being merged into Godot’s master branch: https://github.com/godotengine/godot/pull/17502

Nice!

Basically, it resizes the selection rectangle to fit the dimensions of a sized child, and in cases where there is no sized child it uses a crosshair centered on the actual spawning position of the entity. This looks like it’ll resolve my gripes with the selection square quite well.

Godot 3.1 is currently in beta, so hopefully this will be released soon! Because the release seems imminent, I’ll just keep putting up with the selection square until 3.1 officially comes out.