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