0 votes

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.

asked May 5, 2019 in Engine by CoryParsnipson (21 points)

1 Answer

+2 votes
Best answer
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)
answered May 5, 2019 by volzhs (9,442 points)
selected May 5, 2019 by CoryParsnipson

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!!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.