Skip to content

Commit

Permalink
check if resource for asset already exists before adding it (#3560)
Browse files Browse the repository at this point in the history
# Objective

- Fix #3559 
- Avoid erasing existing resource `Assets<T>` when adding it twice

## Solution

- Before creating a new `Assets<T>`, check if it has already been added to the world


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
Co-authored-by: Aevyrie Roessler <aevyrie@gmail.com>
  • Loading branch information
3 people committed Feb 6, 2022
1 parent 59ee512 commit 75286b8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
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())
}
}

0 comments on commit 75286b8

Please sign in to comment.