Use a Signal Bus.
Yes, you could iterate over the nodes and find all the enemies (e.g. by comparing their script). However, it is easier if all the enemies register themselves to a list (or a group) on _ready
. However, you don’t need any of that.
The insight is this: An object can emit signals of other objects.
We take advantage of that by creating a Signal Bus. Which is a a common pattern in Godot. It goes as follows:
-
Create an autoload (singleton) script. Let us call it
SignalBus
. -
In the script, define signals. And nothing else. *In our case, we define
on_hit
:signal on_hit
-
Every place that needs to emit a signal does it from the signal bus. In this case the enemies do this:
SignalBus.emit_signal("on_hit")
-
And where you need to handle the signal, connect to it. For example on
_ready
. Something like this:func _ready() -> void: SignalBus.connect("on_hit", self, "_on_hit") func _on_hit() -> void: # whatever pass
This way the emitters and receivers of a signal don’t need to know each other. They only need to know the Signal Bus. Which is available everywhere (by virtue of being an autoload).