Await cause error in state machine

Godot Version

4.3

Question

hi i am having a problem of using awaits in in my state machine
when ever i use await i get this error “Trying to call an async function without “await”.” i dont how how to fix this

this is main process

func _process(delta: float) -> void:

	changeStates(currentState.update(delta)) // this line gives error
	label.text = str(currentState.name)
	move_and_slide()


func changeStates(inputState: State):
	if inputState != currentState:
		
		prevState = currentState
		currentState = inputState
		prevState.exit()
		currentState.enter()

and this is the state machine script

extends State

func enter() -> void:
	player.sprites.play("idle")
	player.velocity.x = 0
	
func update(delta: float) -> State:
	player.applyGravity(delta)
	player.flipSpriteToDirection()
	
	await get_tree().create_timer(2).timeout // this is only to show the error

	
	if player.isOnSlope() && player.velocity != Vector2.ZERO:
		return states["slide"]
	
	
	if player.direction.x != 0 && player.is_on_floor():
		return states["run"]
	
	if player.direction.y == 1 && player.is_on_floor():
		
		return states["jump"]
	
	
	return states["idle"]
	
	

func exit() -> void:
	pass

can i use somehow the awaits in this state machine

Okay, it’s like this: your update() method is waiting 2 seconds, so it’s a coroutine now. This must be reflected in your _process method where your call this update function - because it actually returns a State. So you’d have to call it like this:

changeStates(await currentState.update(delta))

Otherwise it wouldn’t know what to do while update is waiting for 2 seconds, as it didn’t get a return value. So it can’t continue, but without the await it also can’t just stop the execution of _process.

I’m not sure if this works, or is even allowed in a _process method.

2 Likes

thank you this solved my problem