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.

It will be:

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 sleep(1.0)
$exit_blocker.set_collision_layer_value(1, false)

You need to add await before sleep like await sleep(1.0)

1 Like

Your sleep() func doesn’t work, because you have call it with await too. Otherwise sleep() itself waits, but the call to sleep(1.0) doesn’t. There’s no way around using await; other than creating a sleep function that takes a Callable as parameter and calling that after the timeout.

1 Like