Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/asset/embedded_asset.rs
6592 views
1
//! Example of loading an embedded asset.
2
3
//! An embedded asset is an asset included in the program's memory, in contrast to other assets that are normally loaded from disk to memory when needed.
4
//! The below example embeds the asset at program startup, unlike the common use case of embedding an asset at build time. Embedded an asset at program startup can be useful
5
//! for things like loading screens, since it might be nice to display some art while other, non-embedded, assets are loading.
6
7
//! One common use case for embedded assets is including them directly within the executable during its creation. By embedding an asset at build time rather than runtime
8
//! the program never needs to go to disk for the asset at all, since it is already located in the program's binary executable.
9
use bevy::{
10
asset::{embedded_asset, io::AssetSourceId, AssetPath},
11
prelude::*,
12
};
13
use std::path::Path;
14
15
fn main() {
16
App::new()
17
.add_plugins((DefaultPlugins, EmbeddedAssetPlugin))
18
.add_systems(Startup, setup)
19
.run();
20
}
21
22
struct EmbeddedAssetPlugin;
23
24
impl Plugin for EmbeddedAssetPlugin {
25
fn build(&self, app: &mut App) {
26
// We get to choose some prefix relative to the workspace root which
27
// will be ignored in "embedded://" asset paths.
28
let omit_prefix = "examples/asset";
29
// Path to asset must be relative to this file, because that's how
30
// include_bytes! works.
31
embedded_asset!(app, omit_prefix, "files/bevy_pixel_light.png");
32
}
33
}
34
35
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
36
commands.spawn(Camera2d);
37
38
// Each example is its own crate (with name from [[example]] in Cargo.toml).
39
let crate_name = "embedded_asset";
40
41
// The actual file path relative to workspace root is
42
// "examples/asset/files/bevy_pixel_light.png".
43
//
44
// We omit the "examples/asset" from the embedded_asset! call and replace it
45
// with the crate name.
46
let path = Path::new(crate_name).join("files/bevy_pixel_light.png");
47
let source = AssetSourceId::from("embedded");
48
let asset_path = AssetPath::from_path(&path).with_source(source);
49
50
// You could also parse this URL-like string representation for the asset
51
// path.
52
assert_eq!(
53
asset_path,
54
"embedded://embedded_asset/files/bevy_pixel_light.png".into()
55
);
56
57
commands.spawn(Sprite::from_image(asset_server.load(asset_path)));
58
}
59
60