|
| 1 | +--- |
| 2 | +title: Asset Saving |
| 3 | +authors: ["@andriyDev"] |
| 4 | +pull_requests: [] |
| 5 | +--- |
| 6 | + |
| 7 | +Since Bevy 0.12, we've had the `AssetSaver` trait. Unfortunately, this trait was not really usable |
| 8 | +for asset saving: it was only intended for use with asset processing! This was a common stumbling |
| 9 | +block for users, and pointed to a gap in our API. |
| 10 | + |
| 11 | +Now, users can save their assets using `save_using_saver`. To use this involves two steps. |
| 12 | + |
| 13 | +### 1. Building the `SavedAsset` |
| 14 | + |
| 15 | +To build the `SavedAsset`, either use `SavedAsset::from_asset`, or `SavedAssetBuilder`. For example: |
| 16 | + |
| 17 | +```rust |
| 18 | +let asset_path: AssetPath<'static> = "my/file/path.whatever"; |
| 19 | +let mut builder = SavedAssetBuilder::new(asset_server.clone(), asset_path.clone()); |
| 20 | + |
| 21 | +let subasset_1 = Line("howdy".into()); |
| 22 | +let subasset_2 = Line("goodbye".into()); |
| 23 | +let handle_1 = builder.add_labeled_asset_with_new_handle( |
| 24 | + "TheFirstLabel", SavedAsset::from_asset(&subasset_1)); |
| 25 | +let handle_2 = builder.add_labeled_asset_with_new_handle( |
| 26 | + "AnotherOne", SavedAsset::from_asset(&subasset_2)); |
| 27 | + |
| 28 | +let main_asset = Book { |
| 29 | + lines: vec![handle_1, handle_2], |
| 30 | +}; |
| 31 | +let saved_asset = builder.build(&main_asset); |
| 32 | +``` |
| 33 | + |
| 34 | +Note that since these assets are borrowed, building the `SavedAsset` should happen in the same async |
| 35 | +task as the next step. |
| 36 | + |
| 37 | +### 2. Calling `save_using_saver` |
| 38 | + |
| 39 | +Now, with a `SavedAsset`, we can just call `save_using_saver` and fill in any arguments: |
| 40 | + |
| 41 | +```rust |
| 42 | +save_using_saver( |
| 43 | + asset_server.clone(), |
| 44 | + &MyAssetSaver::default(), |
| 45 | + &asset_path, |
| 46 | + saved_asset, |
| 47 | + &MySettings::default(), |
| 48 | +).await.unwrap(); |
| 49 | +``` |
| 50 | + |
| 51 | +Part of this includes implementing the `AssetSaver` trait on `MyAssetSaver`. In addition, this is an |
| 52 | +async function, so it is likely you will want to spawn this using `IoTaskPool::get().spawn(...)`. |
0 commit comments