Why does the below code does not print "waiting has completed"?

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

I have written a simple code.
But the problem is code does node print “waiting has completed” at all but the code works fine

extends Node

signal completed
export var n=3

func _ready() -> void:
	print("waiting for 3 sec")
	yield(counter(n, 2.0), "completed")
	print("waiting has completed")

func counter(n:int, wait:float):
	while n>0:
		yield(get_tree().create_timer(wait), "timeout")

Why does the below code does not print “waiting has completed”?

It does for me. Just copied your code into a fresh scene and got (as expected):

waiting for 3 sec
waiting has completed

njamster | 2020-04-08 22:49

some time it works but many time doesn’t work for me.

abecus | 2020-04-09 05:02

:bust_in_silhouette: Reply From: omggomb


counter(n, 2.0)
yield(self, "completed")

in line 7 should work.

Remember that yield expects an object and a signal, so whatever counter() returns will be used as the object in Line 7. This normally wouldn’t work (functions that return nothing, return Null), but since counter() also has a yield statement this is what happens:

counter() will return a GDScriptFunctionState the first time it hits yield in there (Line 15). This is what gets passed into the yield inside _ready. So the yield in line 7 will wait for the signal completed of GDScriptFunctionState (which does exist), and not for the completed signal of your own class.

Also notice that using counter(n, 2.0) will wait 3 * 2 = 6 seconds :).