bevy/crates/bevy_scene/src/scene_loader.rs
Alice Cecile 557ab9897a Make get_resource (and friends) infallible (#4047)
# Objective

- In the large majority of cases, users were calling `.unwrap()` immediately after `.get_resource`.
- Attempting to add more helpful error messages here resulted in endless manual boilerplate (see #3899 and the linked PRs).

## Solution

- Add an infallible variant named `.resource` and so on.
- Use these infallible variants over `.get_resource().unwrap()` across the code base.

## Notes

I did not provide equivalent methods on `WorldCell`, in favor of removing it entirely in #3939.

## Migration Guide

Infallible variants of `.get_resource` have been added that implicitly panic, rather than needing to be unwrapped.

Replace `world.get_resource::<Foo>().unwrap()` with `world.resource::<Foo>()`.

## Impact

- `.unwrap` search results before: 1084
- `.unwrap` search results after: 942
- internal `unwrap_or_else` calls added: 4
- trivial unwrap calls removed from tests and code: 146
- uses of the new `try_get_resource` API: 11
- percentage of the time the unwrapping API was used internally: 93%
2022-02-27 22:37:18 +00:00

44 lines
1.2 KiB
Rust

use crate::serde::SceneDeserializer;
use anyhow::Result;
use bevy_asset::{AssetLoader, LoadContext, LoadedAsset};
use bevy_ecs::world::{FromWorld, World};
use bevy_reflect::TypeRegistryArc;
use bevy_utils::BoxedFuture;
use serde::de::DeserializeSeed;
#[derive(Debug)]
pub struct SceneLoader {
type_registry: TypeRegistryArc,
}
impl FromWorld for SceneLoader {
fn from_world(world: &mut World) -> Self {
let type_registry = world.resource::<TypeRegistryArc>();
SceneLoader {
type_registry: (*type_registry).clone(),
}
}
}
impl AssetLoader for SceneLoader {
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<()>> {
Box::pin(async move {
let mut deserializer = ron::de::Deserializer::from_bytes(bytes)?;
let scene_deserializer = SceneDeserializer {
type_registry: &*self.type_registry.read(),
};
let scene = scene_deserializer.deserialize(&mut deserializer)?;
load_context.set_default_asset(LoadedAsset::new(scene));
Ok(())
})
}
fn extensions(&self) -> &[&str] {
&["scn", "scn.ron"]
}
}