bevy_asset/
direct_access_ext.rs

1//! Add methods on `World` to simplify loading assets when all
2//! you have is a `World`.
3
4use bevy_ecs::world::World;
5
6use crate::{meta::Settings, Asset, AssetPath, AssetServer, Assets, Handle};
7
8/// An extension trait for methods for working with assets directly from a [`World`].
9pub trait DirectAssetAccessExt {
10    /// Insert an asset similarly to [`Assets::add`].
11    fn add_asset<A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A>;
12
13    /// Load an asset similarly to [`AssetServer::load`].
14    fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>;
15
16    /// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
17    fn load_asset_with_settings<'a, A: Asset, S: Settings>(
18        &self,
19        path: impl Into<AssetPath<'a>>,
20        settings: impl Fn(&mut S) + Send + Sync + 'static,
21    ) -> Handle<A>;
22}
23
24impl DirectAssetAccessExt for World {
25    /// Insert an asset similarly to [`Assets::add`].
26    ///
27    /// # Panics
28    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
29    fn add_asset<'a, A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A> {
30        self.resource_mut::<Assets<A>>().add(asset)
31    }
32
33    /// Load an asset similarly to [`AssetServer::load`].
34    ///
35    /// # Panics
36    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
37    fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
38        self.resource::<AssetServer>().load(path)
39    }
40    /// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
41    ///
42    /// # Panics
43    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
44    fn load_asset_with_settings<'a, A: Asset, S: Settings>(
45        &self,
46        path: impl Into<AssetPath<'a>>,
47        settings: impl Fn(&mut S) + Send + Sync + 'static,
48    ) -> Handle<A> {
49        self.resource::<AssetServer>()
50            .load_with_settings(path, settings)
51    }
52}