|
| 1 | +--- |
| 2 | +title: Adding and removing asset sources at runtime |
| 3 | +authors: ["@andriyDev"] |
| 4 | +pull_requests: [] |
| 5 | +--- |
| 6 | + |
| 7 | +Custom asset sources are a great way to extend the asset system to access data from all sorts of |
| 8 | +sources, whether that be a file system, or a webserver, or a compressed package. Unfortunately, in |
| 9 | +previous versions, asset sources could **only** be added before the app starts! This prevents users |
| 10 | +from choosing their sources at runtime. |
| 11 | + |
| 12 | +For a concrete example, consider the case of an application which allows you to pick a `zip` file to |
| 13 | +open. Internally, a `zip` is its own little filesystem. Representing this as an asset source is |
| 14 | +quite natural and allows loading just the parts you need. However, since we couldn't previously add |
| 15 | +asset sources at runtime, this wasn't possible! |
| 16 | + |
| 17 | +Now you can add asset sources quite easily! |
| 18 | + |
| 19 | +```rust |
| 20 | +fn add_source_and_load( |
| 21 | + mut commands: Commands, |
| 22 | + asset_server: Res<AssetServer>, |
| 23 | +) -> Result<(), BevyError> { |
| 24 | + let user_selected_file_path: String = todo!(); |
| 25 | + |
| 26 | + asset_server.add_source( |
| 27 | + "user_directory", |
| 28 | + &mut AssetSourceBuilder::platform_default(&user_selected_file_path, None) |
| 29 | + )?; |
| 30 | + |
| 31 | + let wallpaper = asset_server.load("user_directory://wallpaper.png"); |
| 32 | + commands.spawn(Sprite { image: wallpaper, ..Default::default() }); |
| 33 | + |
| 34 | + Ok(()) |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +Asset sources can also be removed at runtime, allowing you to load and unload asset sources as |
| 39 | +necessary. |
| 40 | + |
| 41 | +We've also changed the behavior of registering asset sources. Previously, you needed to register |
| 42 | +asset sources **before** `DefaultPlugins` (more accurately, the `AssetPlugin`). This was uninuitive, |
| 43 | +and resulted in limitations, like effectively preventing crate authors from registering their own |
| 44 | +asset sources (since crate plugins often need to come after `DefaultPlugins`). Now, asset sources |
| 45 | +need to be registered after `AssetPlugin` (and so, `DefaultPlugins`). |
| 46 | + |
| 47 | +## Limitations |
| 48 | + |
| 49 | +A limitation is that asset sources added after `Startup` **cannot be processed**. Attempting to add |
| 50 | +such a source will return an error. Similarly, removing a processed source returns an error. In the |
| 51 | +future, we hope to lift this limitation and allow runtime asset sources to be processed. |
0 commit comments