|
|
|
 |
Reply From: |
njamster |
It seems to me that between emitting and connecting, that signals are simply a way for performing a function call between two separate scripts/nodes.
You don’t need signals for this! Let’s say you have a tree looking like this:
- Main-Node named "Main" (with a script called main.gd)
- Child-Node named "Child" (with a script called child.gd)
If you then want to call a method foo()
in child.gd from main.gd you’d do:
get_node("Child").foo()
If you instead want to call a method bar()
in main.gd from child.gd you’d do:
get_node("../Main").bar() # alternatively: get_parent().bar()
However, the problem with this is that it explicitly requires a certain tree structure. If you add another child between, these examples will stop working:
- Main-Node named "Main" (with a script called main.gd)
- New-Node named "Killjoy"
- Child-Node named "Child" (with a script called child.gd)
Signals solve this problem by decoupling objects from each other: one node emits a signal - imagine raising your hand in a team meeting - and any other node can decide to either ignore that - like your colleagues >:( - or honor it - like, hopefully, your boss - by executing a special procedure - rising your pay
- each time it’s observed.
Furthermore, signals will come in real handy when running a function that you want to pause at certain points and continue later, after “something” happened. In that case, simply emit a signal after that “something” happened and use the yield-method to suspend the function until that signal is emitted, here’s an example:
Game.gd
var round_id = 0
func _ready():
while true:
round_id += 1
print("Round %d begins!" % round_id)
yield(get_node("Player"), "continue")
print("Round %d ends!" % round_id)
Player.gd
signal continue
func _on_ContinueButton_pressed():
emit_signal("continue")
Yeah, signals+yield was the biggest gain (and mental leap) for me
opyate | 2023-02-24 11:51