11 个版本
0.14.0 | 2024年7月5日 |
---|---|
0.11.0 | 2023年7月13日 |
0.10.2 | 2023年4月7日 |
0.10.1 | 2023年3月28日 |
0.9.3 | 2023年1月17日 |
#128 in 游戏开发
197 每月下载量
在 3 工具包 中使用
31KB
167 行
bevy-tokio-tasks
一个简单的 Bevy 插件,它将 Tokio 运行时集成到 Bevy 应用中。
如何使用
如何初始化此插件
要初始化此插件,只需在初始化您的 Bevy 应用时安装 TokioTasksPlugin
。这样做最简单的方法是使用 TokioTasksPlugin::default()
方法,该方法使用默认设置设置一个 Tokio Runtime
(插件调用 Runtime::enable_all
来启用 Tokio 的 IO 和定时功能)。
fn main() {
bevy::App::new()
.add_plugins(bevy_tokio_tasks::TokioTasksPlugin::default())
}
如果您想自定义 Tokio Runtime
设置,您可以在 TokioTasksPlugin
上指定一个 make_runtime
回调。
fn main() {
bevy::App::new()
.add_plugins(bevy_tokio_tasks::TokioTasksPlugin {
make_runtime: Box::new(|| {
let mut runtime = tokio::runtime::Builder::new_multi_thread();
runtime.enable_all();
runtime.build().unwrap()
}),
..bevy_tokio_tasks::TokioTasksPlugin::default()
})
}
如何启动后台任务
要从 Bevy 系统函数启动后台任务,请将 TokioTasksRuntime
作为资源参数添加,并调用 spawn_background_task
函数。
fn example_system(runtime: ResMut<TokioTasksRuntime>) {
runtime.spawn_background_task(|_ctx| async move {
println!("This task is running on a background thread");
});
}
如何与主线程同步
通常,后台任务需要在某些点与主 Bevy 应用同步。您可以通过在传递给每个后台任务的 TaskContext
上调用 run_on_main_thread
函数来实现这一点。
fn example_system(runtime: ResMut<TokioTasksRuntime>) {
runtime.spawn_background_task(|mut ctx| async move {
println!("This print executes from a background Tokio runtime thread");
ctx.run_on_main_thread(move |ctx| {
// The inner context gives access to a mutable Bevy World reference.
let _world: &mut World = ctx.world;
}).await;
});
}
示例
- change_clear_color - 此示例启动一个无限运行的后台任务。每秒,后台任务更新应用程序的背景清除颜色。这演示了后台任务如何与主线程同步以更新游戏状态。
- current_thread_runtime - 此示例演示了如何自定义 Tokio Runtime。它配置了一个当前线程 Runtime,而不是多线程 Runtime。
- async_fn - 与 change_clear_color 示例执行相同的功能,但它展示了如何将
async fn
传递给spawn_background_task
。 - shutdown_after_sleep - 此示例启动一个后台任务,该任务在 Bevy 游戏更新中睡眠 120 次后关闭 Bevy 应用程序。
版本兼容性
该包的主版本号和次版本号将与 Bevy 匹配。为了允许该包在 Bevy 更新之间发布更新,允许补丁版本独立于 Bevy 的发布周期增加。
bevy-tokio-tasks 版本 | bevy 版本 | tokio 版本 |
---|---|---|
0.14.0 | 0.14.0 | 1 |
0.13.0 | 0.13.0 | 1 |
0.12.0 | 0.12.0 | 1 |
0.11.0 | 0.11.0 | 1 |
0.10.2 | 0.10.1 | 1 |
0.10.1 | 0.10.0 | 1 |
0.10.0 | 0.10.0 | 1 |
0.9.5 | 0.9.1 | 1 |
0.9.4 | 0.9.1 | 1 |
0.9.3 | 0.9.1 | 1 |
0.9.2 | 0.9.1 | 1 |
0.9.1 | 0.9.1 | 1 |
0.9.0 | 0.9.1 | 1 |
依赖
~10–14MB
~239K SLoC