NiklasEi / bevy_asset_loader

Bevy plugin helping with asset loading and organization
Apache License 2.0
449 stars 53 forks source link

allow deriving collections as arrays #218

Open bananaturtlesandwich opened 1 month ago

bananaturtlesandwich commented 1 month ago

as shown in this example in the readme

use bevy::prelude::*;
use bevy_asset_loader::asset_collection::AssetCollection;

#[derive(AssetCollection, Resource)]
struct MyAssets {
    #[asset(paths("images/player.png", "images/tree.png"), collection(typed))]
    files_typed: Vec<Handle<Image>>,
}

you can load collections as vectors but this can be a bit of a waste if you don't intend to mutate the resource (which i assume is the typical use case) so being able to do this as

use bevy::prelude::*;
use bevy_asset_loader::asset_collection::AssetCollection;

#[derive(AssetCollection, Resource)]
struct MyAssets {
    #[asset(paths("images/player.png", "images/tree.png"), collection(typed))]
    files_typed: [Handle<Image>; 2],
}

would be great but implementation would probably need a lot of work

bananaturtlesandwich commented 4 weeks ago

this can be done manually as well for now

impl AssetCollection for MyAssets {
    fn create(world: &mut World) -> Self {
        world.resource_scope(|world, _: Mut<DynamicAssets>| MyAssets {
            files_typed: {
                let asset_server = world
                    .get_resource::<AssetServer>()
                    .expect("Cannot get AssetServer");
                [
                    asset_server.load("images/player.png"),
                    asset_server.load("images/tree.png"),
                ]
            },
        })
    }

    fn load(world: &mut World) -> Vec<UntypedHandle> {
        let cell = world.cell();
        let asset_server = cell
            .get_resource::<AssetServer>()
            .expect("Cannot get AssetServer");
        vec![
            asset_server
                .load_untyped("images/player.png")
                .untyped(),
            asset_server
                .load_untyped("images/tree.png")
                .untyped(),
        ]
    }
}