Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_asset/src/direct_access_ext.rs
6598 views
1
//! Add methods on `World` to simplify loading assets when all
2
//! you have is a `World`.
3
4
use bevy_ecs::world::World;
5
6
use crate::{meta::Settings, Asset, AssetPath, AssetServer, Assets, Handle};
7
8
/// An extension trait for methods for working with assets directly from a [`World`].
9
pub 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
24
impl 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
}
53
54