Using "await" in a loop only functions once

Godot Version

4.2

Question

In my coding situation, I’m using await to wait for a signal (the actual signal doesn’t matter much in this case) in a loop (_process(delta), etc.).

func _process(delta): await get_tree().create_timer(1).timeout print("i")
When I run a project with this script on a node, it will wait one second for the timer, then print “i” every frame until I close the project. I would expect it would wait for one second, then print “i”, then wait, and so on. How would you go about correcting the code so it would wait for a signal, run some code, the loop over again?
(short of using an actual signal function)

1 Like

this is actually waited a signal of “timeout” from script-code-created Timer

Ok, so it seems like the way await works in a loop is it acts once, even though the code is being continually processed. Is there any real way to make it work inside a loop, creating a new timer and waiting for its timeout every iteration?

in func _process(delta):

store accumulated delta, if it hits 1 second (example), it reset back to 0. but when it hit 1 second (in an IF branch), call the method you wanted to use. there’s no need to use timer for this


var time=0.0
func _process(delta):
	time+=delta
	if time>=1.0:
		time=0.0
		print("1 second pass, call your method here")

Thanks for your response! That’s a good method of timesteps, but I’m trying to await a signal from another node, not specifically a timer. (The timer in my code example was showing the code was supposed to wait for a signal, not a timer specifically. My apologies for not being very clear.)

The _process() function is a callback that will be called each frame. it won’t stop the processing of the node if you await inside it.

If you want to stop the processing of the node until the await signal is fired then you can try something like this:

func _process(delta: float) -> void:
	set_process(false) # Stop the _process() function
	await get_tree().create_timer(1).timeout # wait 1 second
	set_process(true) # start again the _process() function
	print("hello")
1 Like

Ok, thanks so much! I appreciate your help.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.