How to create a "sleep" using another function in 4.2.2?

Godot Version

Running 4.2.2.

Question

I’m creating a function that opens a door, waits a little bit, and allows the player through. It functions perfectly if I use the commonly-accepted

await get_tree().create_timer(seconds).timeout

where “seconds” is a float. However, that’s lengthy. To save time, I tried creating a global function that goes as follows:

func sleep(seconds: float)->void:
await get_tree().create_timer(seconds).timeout

When I run this function, it doesn’t do anything. Here’s the full code for reference:

Works:

var door_opened = false
func _process(delta):
if Input.is_action_just_pressed(“interact”) and player_in_interaction_zone == true:
if door_opened == true:
return
else:
door_opened = true
$door_animation.play(“door_opening”)
await get_tree().create_timer(1.0).timeout
$exit_blocker.set_collision_layer_value(1, false)

Doesn’t work:

var door_opened = false
func _process(delta):
if Input.is_action_just_pressed(“interact”) and player_in_interaction_zone == true:
if door_opened == true:
return
else:
door_opened = true
$door_animation.play(“door_opening”)
sleep(1.0)
$exit_blocker.set_collision_layer_value(1, false)

Note that the function doesn’t work regardless of which script it’s in; setting it in my global script and calling it with global.sleep(1.0) also does nothing.

Please help! I’m reasonably sure it has something to do with _process(), but I’ve scoured the documentation and can’t find the issue.

change to

await sleep(1.0)

And for context, the documentation is here - you want the section titled Awaiting for signals or coroutines.

Basically: When you make a function that awaits something, that function is automatically treated as a coroutine, which you can await. If you call it without await, one of two things can happen:

  • If you try to do anything with the return value, it causes an error (because it won’t have a return value until the coroutine is done running).
  • If, like in your case, you just call it without trying to get a return value, it’ll still start the coroutine (so your timer still gets created and started), but the calling function (in your case the _process function) will just continue executing without waiting for sleep to finish.

I think it is already solved so delete it

why some people double posts like this, this one should be closed or deleted
same post here:

1 Like