Godot Signals allows you to “signal” listening nodes to take action when that signal is fired off from another node. It’s an observer pattern. It is used as a better alternative then constantly polling to see if something has occurred.
It can decouple your code so everything becomes more manageable. You can either create your signal in the editor or you actually can do it through code completely. This is usually necessary when you’re instancing nodes via code.
Built in Signals can be context sensitive to their respective nodes. A button node for instance might have a signal for being pressed, or released, while a timer node, might have a signal for when the timer runs out. If the built in functionality doesn’t do what you want, you always can code what you need yourself.
I’ll show you how to do Signals completely in code. In your code, to add a signal just type in
signal code_alert
once that’s done, you can see your new signal in the editor and it can be connected like a regular built-in signal.
You also can fire off the signal in code by using emit.
emit_signal("code_alert")
You also can pass arguments when emitting the signal.
emit_signal("code_alert", "File not found")
Once the signal is caught, it could read the message of the file can’t be found.
You also are not limited to just one argument and can pass many arguments. These could be things regarding health, damage, items, or anything else that you’d like to update between scenes.
To not use the editor, you can just use connect where the first argument is the signal name, the second argument is the node to reference, and the third argument is the function name that you want to run.
node.connect("quit", self, "go_to_main_menu")
Here’s a small example
var node = resource.instance()
for child in get_children():
remove_child(child)
child.queue_free()
add_child(node)
node.connect("quit", self, "go_to_main_menu")
This is not a sponsored post, but there are affiliate links in this post which will earn me a small percentage of your purchase.