Crate bevy_asset_loader

source ·
Expand description

The goal of this crate is to offer an easy way for bevy games to load all their assets in a loading State.

bevy_asset_loader introduces the derivable trait AssetCollection. Structs with asset handles can be automatically loaded during a configurable loading State. Afterwards they will be inserted as resources containing loaded handles and the plugin will switch to a second configurable State.


fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_state::<GameState>()
        .add_loading_state(
            LoadingState::new(GameState::Loading)
                .continue_to_state(GameState::Next)
                .load_collection::<AudioAssets>()
                .load_collection::<ImageAssets>()
        )
        .add_systems(Update, use_asset_handles.run_if(in_state(GameState::Next)))
        .run();
}

#[derive(AssetCollection, Resource)]
struct AudioAssets {
    #[asset(path = "audio/background.ogg")]
    background: Handle<AudioSource>,
    #[asset(path = "audio/plop.ogg")]
    plop: Handle<AudioSource>
}

#[derive(AssetCollection, Resource)]
pub struct ImageAssets {
    #[asset(path = "images/player.png")]
    pub player: Handle<Image>,
    #[asset(path = "images/tree.png")]
    pub tree: Handle<Image>,
}

// since this function runs in MyState::Next, we know our assets are loaded.
// We can get their handles from the AudioAssets resource.
fn use_asset_handles(mut commands: Commands, audio_assets: Res<AudioAssets>) {
    commands.spawn(AudioBundle {
        source: audio_assets.background.clone(),
        ..default()
    });
}

#[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
enum GameState {
    #[default]
    Loading,
    Next
}

Modules§