Skip to content

Commit c1bbab5

Browse files
mockersfnicopap
authored andcommitted
Scene example: write file in a task (#5952)
# Objective - Fix #5951 - Improve on #5949 by not risking blocking a system ## Solution - Wrap file writing in a task
1 parent 9145fc5 commit c1bbab5

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

examples/scene/scene.rs

+17-11
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
use std::fs::File;
33
use std::io::Write;
44

5-
use bevy::{prelude::*, utils::Duration};
5+
use bevy::{prelude::*, tasks::IoTaskPool, utils::Duration};
66

77
fn main() {
88
App::new()
@@ -104,17 +104,23 @@ fn save_scene_system(world: &mut World) {
104104
let scene = DynamicScene::from_world(&scene_world, type_registry);
105105

106106
// Scenes can be serialized like this:
107-
info!("{}", scene.serialize_ron(type_registry).unwrap());
108-
109-
// Write the scene RON data to file (leveraging From<io::Error> for ron::error::Error)
110-
File::create(format!("assets/{}", NEW_SCENE_FILE_PATH))
111-
.map_err(|err| err.into())
112-
.and_then(|mut file| {
113-
scene
114-
.serialize_ron(type_registry)
115-
.and_then(|data| file.write(data.as_bytes()).map_err(|err| err.into()))
107+
let serialized_scene = scene.serialize_ron(type_registry).unwrap();
108+
109+
// Showing the scene in the console
110+
info!("{}", serialized_scene);
111+
112+
// Writing the scene to a new file. Using a task to avoid calling the filesystem APIs in a system
113+
// as they are blocking
114+
// This can't work in WASM as there is no filesystem access
115+
#[cfg(not(target_arch = "wasm32"))]
116+
IoTaskPool::get()
117+
.spawn(async move {
118+
// Write the scene RON data to file
119+
File::create(format!("assets/{}", NEW_SCENE_FILE_PATH))
120+
.and_then(|mut file| file.write(serialized_scene.as_bytes()))
121+
.expect("Error while writing scene to file");
116122
})
117-
.expect("Error while writing scene to file");
123+
.detach();
118124
}
119125

120126
// This is only necessary for the info message in the UI. See examples/ui/text.rs for a standalone

0 commit comments

Comments
 (0)