Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - check if resource for asset already exists before adding it #3560

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/bevy_asset/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ rand = "0.8.0"

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { version = "0.2" }
web-sys = { version = "0.3", features = ["Request", "Window", "Response"]}
web-sys = { version = "0.3", features = ["Request", "Window", "Response"] }
wasm-bindgen-futures = "0.4"
js-sys = "0.3"

Expand All @@ -44,3 +44,4 @@ ndk-glue = { version = "0.5" }
[dev-dependencies]
futures-lite = "1.4.0"
tempfile = "3.2.0"
bevy_core = { path = "../bevy_core", version = "0.6.0" }
29 changes: 29 additions & 0 deletions crates/bevy_asset/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,16 @@ pub trait AddAsset {
}

impl AddAsset for App {
/// Add an [`Asset`] to the [`App`].
///
/// Adding the same [`Asset`] again after it has been added does nothing.
fn add_asset<T>(&mut self) -> &mut Self
where
T: Asset,
{
if self.world.contains_resource::<Assets<T>>() {
return self;
}
let assets = {
let asset_server = self.world.get_resource::<AssetServer>().unwrap();
asset_server.register_asset_type::<T>()
Expand Down Expand Up @@ -305,3 +311,26 @@ impl AddAsset for App {
self
}
}

#[cfg(test)]
mod tests {
use bevy_app::App;

use crate::{AddAsset, Assets};

#[test]
fn asset_overwriting() {
#[derive(bevy_reflect::TypeUuid)]
#[uuid = "44115972-f31b-46e5-be5c-2b9aece6a52f"]
struct MyAsset;
let mut app = App::new();
app.add_plugin(bevy_core::CorePlugin)
.add_plugin(crate::AssetPlugin);
app.add_asset::<MyAsset>();
let mut assets_before = app.world.get_resource_mut::<Assets<MyAsset>>().unwrap();
let handle = assets_before.add(MyAsset);
app.add_asset::<MyAsset>(); // Ensure this doesn't overwrite the Asset
let assets_after = app.world.get_resource_mut::<Assets<MyAsset>>().unwrap();
assert!(assets_after.get(handle).is_some())
}
}