Coroutines: A computer component that generalizes subroutines for non-preemptive multitasking by allowing execution to be suspended and resumed.
Subroutines: a set of instructions designed to perform a frequently used operation within a program
To understand coroutines, we need to know how sequential processing works.
Sequential processing runs code line by line in sequence, from start to finish in the order it is received in.
In GDScript, your code runs sequentially unless otherwise specified (threads).
Let’s take a look at this example:
func _ready():
addHealth(10)
print('finished!')
func addHealth(lifePoints):
print('lifePoints called!')
Now let us look at how the code runs sequentially.
Typically, code is run line by line. A function has code inside which needs to run everything first, and only take a brief moment to pause if a function has been called.
Such is the case where the _ready()
method will run all the code inside its block unless another
method has been called, in which the block will be pause and move onto the newly called function (addHealth(lifepoints)
).
To use coroutines, you will need to use two methods, the yield
method and the
resume
method.
The yield
method pauses a function, while the resume
method will continue the
yielded method.
func _ready():
var pausedFunction = addHealth(10)
print('finished!')
pausedFunction.resume() # resume the addHealth call
func addHealth(lifePoints):
yield() # pause the function
print('lifePoints called!')
To learn more about coroutines and yield in the context of GDScript, check out this great resource from GDScript Dude.
Coroutines | Godot GDScript Tutorial | Ep 26 video & article by Godot Tutorials is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .