Skip to main content

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, LoadBuilder};
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    /// Creates a new [`LoadBuilder`] similar to [`AssetServer::load_builder`].
17    fn load_builder(&self) -> LoadBuilder<'_>;
18
19    /// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
20    #[deprecated(note = "Use `world.load_builder().with_settings(settings).load(path)`")]
21    fn load_asset_with_settings<'a, A: Asset, S: Settings>(
22        &self,
23        path: impl Into<AssetPath<'a>>,
24        settings: impl Fn(&mut S) + Send + Sync + 'static,
25    ) -> Handle<A>;
26}
27
28impl DirectAssetAccessExt for World {
29    /// Insert an asset similarly to [`Assets::add`].
30    ///
31    /// # Panics
32    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
33    fn add_asset<'a, A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A> {
34        self.resource_mut::<Assets<A>>().add(asset)
35    }
36
37    /// Load an asset similarly to [`AssetServer::load`].
38    ///
39    /// # Panics
40    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
41    fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
42        self.resource::<AssetServer>().load(path)
43    }
44
45    /// Creates a new [`LoadBuilder`] similar to [`AssetServer::load_builder`].
46    ///
47    /// # Panics
48    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
49    fn load_builder(&self) -> LoadBuilder<'_> {
50        self.resource::<AssetServer>().load_builder()
51    }
52
53    /// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
54    ///
55    /// # Panics
56    /// If `self` doesn't have an [`AssetServer`] resource initialized yet.
57    fn load_asset_with_settings<'a, A: Asset, S: Settings>(
58        &self,
59        path: impl Into<AssetPath<'a>>,
60        settings: impl Fn(&mut S) + Send + Sync + 'static,
61    ) -> Handle<A> {
62        self.resource::<AssetServer>()
63            .load_builder()
64            .with_settings(settings)
65            .load(path.into())
66    }
67}