GODOT - Signal not connecting when using connect(). Function is not getting executed

Viewed 1284

Here is the link to the files:

signal_test.gd

extends Node2D
signal do

func _ready() -> void:
    print('signal_ready!')
    emit_signal('do')
    pass

test.gd

extends Node2D

onready var signal_test = preload('res://signal_test.tscn')

func _ready() -> void:
    print('test ready')

func _process(delta: float) -> void:
    if Input.is_action_just_pressed("jump"):
        var h = signal_test.instance()
        add_child(h)
        h.connect('do', self, 'do')
        print(h.is_connected('do', self, 'do'))

func do():
    print('DONE CONNECTING!!')

The test.gd file creates an instance of a node and connect it to it's function using the connect() method. But the function is not getting executed. It only says true when I use is_connected() on the test.tscn, but false on the instance of the node. Anyone know why?

1 Answers

The signal will be emitted in _ready, which will execute after the node is added as child, before the next line:

var h = signal_test.instance()
add_child(h)
# <-- signal emitted here, it is NOT connected
h.connect('do', self, 'do')

Solution: connect the signal before adding the node as child:

var h = signal_test.instance()
h.connect('do', self, 'do')
add_child(h)
# <-- signal emitted here, it is connected
Related