extra_asset_source/extra_source.rs
1//! An example of registering an extra asset source, and loading assets from it.
2//! This asset source exists in addition to the default asset source.
3
4use bevy::{
5 asset::{
6 io::{AssetSourceBuilder, AssetSourceId},
7 AssetPath,
8 },
9 prelude::*,
10};
11use std::path::Path;
12
13fn main() {
14 App::new()
15 // Add an extra asset source with the name "example_files" to
16 // AssetSourceBuilders.
17 //
18 // This must be done before AssetPlugin finalizes building assets.
19 .register_asset_source(
20 "example_files",
21 AssetSourceBuilder::platform_default("examples/asset/files", None),
22 )
23 // DefaultPlugins contains AssetPlugin so it must be added to our App
24 // after inserting our new asset source.
25 .add_plugins(DefaultPlugins)
26 .add_systems(Startup, setup)
27 .run();
28}
29
30fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
31 commands.spawn(Camera2d);
32
33 // Now we can load the asset using our new asset source.
34 //
35 // The actual file path relative to workspace root is
36 // "examples/asset/files/bevy_pixel_light.png".
37 let path = Path::new("bevy_pixel_light.png");
38 let source = AssetSourceId::from("example_files");
39 let asset_path = AssetPath::from_path(path).with_source(source);
40
41 // You could also parse this URL-like string representation for the asset
42 // path.
43 assert_eq!(asset_path, "example_files://bevy_pixel_light.png".into());
44
45 commands.spawn(Sprite::from_image(asset_server.load(asset_path)));
46}