gdext_coroutines
"Run Rust coroutines and async code in Godot 4.2+ (through GDExtension), inspired on Unity's Coroutines design."
Beware
This crate uses 5 nightly(unstable) features:
It also requires GdExtension's experimental_threads
feature
Setup
Add the dependency to your Cargo.toml file:
[]
= "0.7"
What does this do?
Allows you to execute code in an asynchronous manner, the coroutines of this crate work very much like Unity's.
It also allows you to execute async code(futures), the implementation uses the crate smol
and requires the feature async
.
use *;
use *;
For more examples, check the integration_tests
folder in the repository.
How does this do?
A Coroutine is a struct that derives Node
When you invoke start_coroutine()
, start_async_task()
, or spawn()
, a SpireCoroutine
node is created, then added as a child of the caller.
Then, on every frame:
- Rust Coroutines(
start_coroutine
): polls the current yield to advance its inner function. - Rust Futures(
start_async_task
): checks if the future has finished executing.
Then it automatically destroys itself after finishing:
Since the coroutine is a child node of whoever created it, the behavior is tied to its parent:
- If the parent exits the scene tree, the coroutine pauses running (since it requires
_process/_physics_process
to run). - If the parent is queued free, the coroutine is also queued free, and its
finished
signal never triggers.
Notes
1 - You can await coroutines from GdScript, using the signal finished
var coroutine: SpireCoroutine = ..
var result = await coroutine.
result
contains the return value of your coroutine/future.
2 - You can make your own custom types of yields, just implement the trait KeepWaiting
Then you can use that trait like this:
let my_custom_yield: dyn KeepWaiting = ...;
yield Dyn;
3 - Your main crate must have at least one godot class defined in it
Otherwise, this crate's godot classes will not be registered in Godot.
This is a known issue in gdext-rust, it's not related to gdext-coroutines.