TExcelTAD
Home › Godot 4 with GDScript › await & Coroutines

await & Coroutines

Games are full of sequences that span time: "flash red, wait 0.2 s, flash back", "show the text, wait for a click, show the next line", "count down 3, 2, 1, GO". Written with frame callbacks, each becomes a state variable and a timer check in _process. await lets you write them top to bottom: the function pauses at await until a signal fires, and the rest of the game keeps running meanwhile.

await replaces Godot 3's yield. A function that contains await is a coroutine.

Waiting for a timer

get_tree().create_timer(seconds) creates a one-off SceneTreeTimer and returns it. Awaiting its timeout signal pauses the function for that long:

gdscript · try it yourself
extends Node

# frames: 120
func _ready():
	print("frame ", Engine.get_process_frames(), ": intro starts")
	countdown()
	print("frame ", Engine.get_process_frames(), ": _ready returned")

func countdown() -> void:
	for n in [3, 2, 1]:
		print("frame ", Engine.get_process_frames(), ": ", n)
		await get_tree().create_timer(0.5).timeout
	print("frame ", Engine.get_process_frames(), ": GO!")
frame 0: intro starts
frame 0: 3
frame 0: _ready returned
frame 30: 2
frame 61: 1
frame 92: GO!

Read the order carefully:

  1. countdown() runs until its first await, prints 3, and then returns to the caller immediately. _ready continues and prints _ready returned in the same frame.
  2. Half a second later (30 frames at 60 FPS) the timer fires and countdown resumes where it stopped.
  3. Timers tick once per frame, so a wait ends on the first frame at or after its time. A timer created in the middle of a frame starts counting on the next one, which is why the later steps land on frames 61 and 92 rather than 60 and 90. Never use chains of short awaits as a precise clock; for exact timing, accumulate delta yourself.

create_timer() has optional arguments: create_timer(time, process_always = true, process_in_physics = false, ignore_time_scale = false). With the default process_always = true the timer keeps running while the tree is paused, so a "wait 2 s" in gameplay code also counts down behind the pause menu. Pass false for gameplay waits.

Waiting for a signal, a function or the next frame

You can await any signal, and you can await a call to another coroutine to get its return value:

gdscript · try it yourself
extends Node

# frames: 90
signal door_opened(by: String)

func _ready():
	run_cutscene()
	var t := get_tree().create_timer(1.0)
	t.timeout.connect(func(): door_opened.emit("guard"))

func roll_dice() -> int:
	await get_tree().create_timer(0.25).timeout
	return 4

func run_cutscene() -> void:
	var value := await roll_dice()
	print("frame ", Engine.get_process_frames(), ": rolled ", value)
	var who: String = await door_opened
	print("frame ", Engine.get_process_frames(), ": door opened by ", who)
	await get_tree().process_frame
	print("frame ", Engine.get_process_frames(), ": one frame later")
	await get_tree().physics_frame
	print("physics frame done, cutscene over")
frame 15: rolled 4
frame 59: door opened by guard
frame 60: one frame later
physics frame done, cutscene over
You write It waits for
await get_tree().create_timer(0.5).timeout a delay
await $AnimationPlayer.animation_finished an animation to end
await tween.finished a tween (see Timers & Tweens)
await button.pressed a click
await some_signal the signal; with one argument, await returns it; with several, an Array
await get_tree().process_frame the next frame (useful after add_child or queue_free)
await get_tree().physics_frame the next physics step
var x = await coroutine() the coroutine to finish, then its return value

roll_dice() contains await, so it is a coroutine. Using its result without await (var value = roll_dice()) is a parse error: Function "roll_dice()" is a coroutine, so it must be called with "await". Calling a coroutine as a plain statement, as _ready does with run_cutscene(), is allowed and starts it "in the background". If you await a function that never awaits, Godot just calls it (and the editor warns about the redundant await).

When the node is freed mid-wait

A coroutine belongs to its object. If the object is freed while the coroutine waits, the coroutine is simply dropped and never resumes:

gdscript · try it yourself
extends Node

# frames: 60
class Enemy extends Node:
	func flash_then_attack() -> void:
		print(name, ": winding up")
		await get_tree().create_timer(0.5).timeout
		print(name, ": attack!")

func _ready():
	for n in ["Orc", "Bat"]:
		var e := Enemy.new()
		e.name = n
		add_child(e)
		e.flash_then_attack()
	await get_tree().create_timer(0.2).timeout
	get_node("Bat").queue_free()
	print("Bat freed")
	await get_tree().create_timer(0.5).timeout
	print("done")
Orc: winding up
Bat: winding up
Bat freed
Orc: attack!
done

That is usually what you want, but it has a trap: code after an await must not assume the world is unchanged. The player may have died, the level may have been reloaded, or another node you stored in a variable may have been freed. After a long wait, check what you rely on:

gdscript
func explode_later(target: Node2D) -> void:
	await get_tree().create_timer(1.5, false).timeout
	if not is_instance_valid(target):     # freed while we waited
		return
	target.take_damage(10)

Coroutine or state machine?

await is great for linear scripted sequences: cutscenes, tutorials, dialogue, spawn waves, "do X, wait, do Y". It is a poor fit for behaviour that must react to interruptions at any moment (an enemy that can be stunned during its wind-up, a jump that can be cancelled), because there is no built-in way to cancel a waiting coroutine from outside. For those, use a timer variable or a state machine and decide every frame. A common compromise is a generation counter: increment it to "cancel", and have the coroutine return when the value changed while it waited.

gdscript
var _attack_id := 0

func start_attack() -> void:
	_attack_id += 1
	var my_id := _attack_id
	await get_tree().create_timer(0.6, false).timeout
	if my_id != _attack_id:   # a newer attack or a stun cancelled this one
		return
	deal_damage()

func stun() -> void:
	_attack_id += 1           # invalidates any pending attack

Test yourself

_ready() calls countdown(), which hits await on its first line. What happens to _ready?

  1. It blocks until the countdown is finished
  2. It continues immediately; countdown resumes later when the awaited signal fires
  3. It is called again
  4. The game freezes

What happens to a coroutine that is waiting on a timer when its node is freed?

  1. It resumes and crashes
  2. It is dropped and never resumes
  3. It finishes instantly
  4. It moves to the parent node

A gameplay delay uses get_tree().create_timer(2.0). Why might it finish while the game is paused?

  1. Timers ignore delta
  2. process_always defaults to true, so the timer also runs while the tree is paused
  3. SceneTreeTimers use real wall-clock time only
  4. Pausing doubles the speed