Can't connect timer signal through GDscript (GUI method fine)

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

Hi, I was trying to create a timer and connect it to my gdscript completely programmatically. I followed some examples online but for some reason, the connection wouldn’t work. If I create a timer in the GUI and then use the inspector to hook up the signal, everything works fine. I would like to find out how to do it in the script, though. Is this a bug or something that is just not possible to do through scripting?

Example gdscript code that does not work:

var timer
    
func _ready():
   timer = Timer.new()
   timer.set_wait_time(2)
   timer.connect("timeout", self, "_on_timer_timeout")

   if self.is_connected("timeout", timer, "_on_timer_timeout"):
      print ("YES")
   else:
      print ("NO")

func _process(delta):
   if (Input.is_action_pressed("ui_up")):
      timer.start()

func _on_timer_timeout():
      print ("TIMEOUT")

============

In the console, it prints out “NO” to indicate that the connection was apparently not successful? And if I press the up arrow exactly once, nothing happens.

:bust_in_silhouette: Reply From: volzhs
timer.connect("timeout", self, "_on_timer_timeout")

you connected timer node to _on_timer_timeout with timeout signal.

if self.is_connected("timeout", timer, "_on_timer_timeout"):

but you checked if self node is connected to _on_timer_timeout with timeout signal.
you should check it with timer node, not self

if timer.is_connected("timeout", timer, "_on_timer_timeout"):

and the Timer is a Node should be added to scene.
it won’t do anything before is added to scene.

timer = Timer.new()
add_child(timer)

Ah thanks! I’m still new at this…

Just for future reference, here’s my code after I made your changes:

var timer

func _ready():
   timer = Timer.new()
   timer.set_wait_time(2)
   add_child(timer)
   timer.connect("timeout", self, "_on_timer_timeout")

   if timer.is_connected("timeout", self, "_on_timer_timeout"):
      print ("YES")
   else:
      print ("NO")

func _process(delta):
   if (Input.is_action_pressed("ui_up")):
      timer.start()

func _on_timer_timeout():
      print ("TIMEOUT")

Works perfectly now. Thanks!!

CoryParsnipson | 2019-05-05 17:01