Signal connection using UI vs Code - Timing is off.

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

I’m working through the tutorial, trying to understand signals.
I have a parent who will receive a custom signal from a child and then print to console.

Currently, when I call Object.connect() at runtime in the parent, the child is _ready first and therefore emits its signal before the parent has a chance to connect a listener.
Therefore, the signal can’t be processed and nothing happens.

However, if I use the UI and connect my custom signal using the Node’s Signal connection interface, then the parent does connect before the child is _ready and processes the emitted signal.

Now, I could yield in the child and specifically wait for the parent’s _ready function manually, but I’m wondering how I can write the code to mimic the timing of what happens when I connect the signal in the editor?

Parent:

extends Node2D
func _ready():
  $Timer.connect("my_signal", self, "_on_Timer_my_signal")

func _on_Timer_my_signal():
  print("my signal made it!")

Child (node named Timer):

extends Timer
signal my_signal

func _ready():
  print("emitting signal")
  emit_signal("my_signal")
:bust_in_silhouette: Reply From: wyattb

Try this for the child by using call_deferred:

extends Timer
signal my_signal

func _ready():
	print("emitting signal")
	call_deferred("emit_signal","my_signal")
:bust_in_silhouette: Reply From: Dove Leiger

You may find it helpful to let the child node connect its signal to the parent node, rather than the other way around. Firstly, because the child’s _ready() method will fire before the parent’s and so avoid the problem you had, and secondly, it avoids the possibility that the child node may be changed or removed in the editor, or at runtime, and the parent would try to connect to a nonexistent child. You will never have the opposite problem, a child trying to connect a signal to a nonexistent parent, because if the parent were removed, it would take the child with it.