#Godot 4: Can I cancel/stop a coroutine that's in progress?

4 messages · Page 1 of 1 (latest)

azure cape
#

Say I want to script an enemy AI's behavior with coroutines using await and timers, i.e. something like this

func _ready():
  var coroutine = await AI()

func AI():
  while true:

    # crouch for 1 second
    animator.play("crouch")
    await get_tree().create_timer(1).timeout

    # jump and wait for landing
    animator.play("jump")
    jump()
    await landed

    # repeat cycle

Is there a way to cancel the coroutine after it's started? i.e., if the entity died, I would want to immediately interrupt the coroutine and play a death animation.

fair perch
#

No you can't. Which is why it can be better to avoid using await and instead just use signal callbacks and some kind of state machine

azure cape
#

bummer, thanks! I'll look into signals then

neon lantern
#

In C# it is a standard feature of async function. I used it to stop long working process. So it is possible but not with GD script.