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
8pub trait DirectAssetAccessExt {
9    /// Insert an asset similarly to [`Assets::add`].
10    fn add_asset<A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A>;
11
12    /// Load an asset similarly to [`AssetServer::load`].
13    fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>;
14
15    /// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
16    fn load_asset_with_settings<'a, A: Asset, S: Settings>(
17        &self,
18        path: impl Into<AssetPath<'a>>,
19        settings: impl Fn(&mut S) + Send + Sync + 'static,
20    ) -> Handle<A>;
21}
22impl DirectAssetAccessExt for World {
23    /// Insert an asset similarly to [`Assets::add`].
24    ///
25    /// # Panics
26    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
27    fn add_asset<'a, A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A> {
28        self.resource_mut::<Assets<A>>().add(asset)
29    }
30
31    /// Load an asset similarly to [`AssetServer::load`].
32    ///
33    /// # Panics
34    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
35    fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
36        self.resource::<AssetServer>().load(path)
37    }
38    /// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
39    ///
40    /// # Panics
41    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
42    fn load_asset_with_settings<'a, A: Asset, S: Settings>(
43        &self,
44        path: impl Into<AssetPath<'a>>,
45        settings: impl Fn(&mut S) + Send + Sync + 'static,
46    ) -> Handle<A> {
47        self.resource::<AssetServer>()
48            .load_with_settings(path, settings)
49    }
50}