Using assets
Read and change loaded assets through Assets<T>, how handles and asset ids keep assets alive, react to AssetEvent messages, and add assets made at runtime.
Every loaded asset lives in an Assets<T> resource, one per asset type. Your systems read it with Res<Assets<T>>, change it with ResMut<Assets<T>>, and find an asset with its handle or id.
Look an asset up#
use neo::prelude::*;
#[derive(Resource)]
struct LevelMesh(Handle<Mesh>);
fn count_vertices(meshes: Res<Assets<Mesh>>, level: Res<LevelMesh>) {
// None until the mesh has loaded (or if it failed)
let Some(mesh) = meshes.get(&level.0) else { return };
info!("{} vertices", mesh.count_vertices());
}| Method | What it does |
|---|---|
get(id) | Option<&T>. Takes a &Handle<T>, a Handle<T>'s id() or an AssetId<T>. |
get_mut(id) | Option<AssetMut<T>>. Changing it sends AssetEvent::Modified, and the renderer re-uploads meshes, images and materials. |
add(value) | Stores a new asset and returns a strong Handle<T>. |
insert(id, value) | Stores an asset under an id you already have, such as a reserved handle's. Returns a Result. |
reserve_handle() | A handle for an asset you'll insert later. |
remove(id) | Removes and returns the asset. |
contains(id), len(), is_empty() | What's stored. |
iter(), iter_mut(), ids() | Every asset of this type. |
Handles and ids#
| Type | What it is |
|---|---|
Handle<T> | Handle::Strong: counts as a user of the asset. When the last strong handle is dropped, the asset is unloaded. Handle::Uuid: a fixed id that never unloads anything, for assets you insert yourself under a constant. |
AssetId<T> | A small, Copy id for an asset (handle.id()). It doesn't keep the asset alive; use it in maps and messages. |
UntypedHandle, UntypedAssetId | The same without the type, for code that handles many asset types. typed::<T>() converts back. |
Keep a strong handle wherever the asset must stay loaded: in a component (Mesh3d(handle), Sprite { image, .. }), in a resource, or in another asset. Cloning a handle is cheap.
A constant handle for an asset your code inserts:
use neo::asset::uuid_handle;
const FLASH: Handle<Image> = uuid_handle!("1347c9b7-c46a-48e7-b7b8-023a354b7cac");
fn make_flash(mut images: ResMut<Assets<Image>>) {
images.insert(&FLASH, Image::default()).unwrap();
}Asset events#
The asset system sends an AssetEvent<T> message whenever an asset of type T changes. Read them with a MessageReader:
fn on_mesh_events(mut events: MessageReader<AssetEvent<Mesh>>, level: Res<LevelMesh>) {
for event in events.read() {
if event.is_loaded_with_dependencies(&level.0) {
info!("level mesh ready");
}
if let AssetEvent::Modified { id } = event {
info!("mesh {id} changed");
}
}
}| Event | When |
|---|---|
Added { id } | The asset was stored, by a load or by add / insert. |
Modified { id } | The asset was changed through get_mut, or reloaded. |
Removed { id } | The asset was removed. |
Unused { id } | Its last strong handle was dropped. |
LoadedWithDependencies { id } | It and everything it depends on have loaded. |
Each event has a matching check: is_added(id), is_modified(id), is_removed(id), is_unused(id) and is_loaded_with_dependencies(id).
To run a system only when something happened, use the on_message run condition:
app.add_systems(Update, refresh_ui.run_if(on_message::<AssetEvent<Image>>));Assets made at runtime#
You don't need a file to have an asset. Build the value and add it:
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb(0.8, 0.7, 0.6),
..default()
})),
));
}For an asset that takes a while to build, asset_server.add_async(future) returns a handle at once and stores the asset when the future finishes, on the engine's task pool:
async fn build_terrain() -> Result<Mesh, std::io::Error> {
Ok(Mesh::from(Plane3d::default().mesh().size(64.0, 64.0)))
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Mesh3d(asset_server.add_async(build_terrain())));
}Or reserve a handle now with assets.reserve_handle() and insert the value later. Examples: cargo run --example generated_assets, cargo run --example alter_sprite.