Are signals just function calls between scripts?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By toec

I’m not looking to change the definition of such things here, but merely trying to relate how signals work with past experience with other programming languages.

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.

The “emit signal” is the function call from script A, and the act of connecting with script B tells script B to be aware that Script A is going to call a function contained within script B.

So… am i on the right track with this? Is this just a bare minimum function of signals where as I learn more and go further, signals become useful for other things?

:bust_in_silhouette: 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 :smiley: - 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