bevy_asset: Add LoadContext::get_handle_untyped (#8470)

# Objective

Currently, there isn't a clean way of getting an untyped handle to an
asset during asset loading. This is useful for when an asset needs to
reference other assets, but may not know the concrete type of each
asset.

We could "hack" this together by just using some random asset:

```rust
// We don't care what `bar.baz` is, so we "pretend" it's an `Image`
let handle: Handle<Image> = load_context.get_handle("foo/bar.baz");
```

This should work since we don't actually care about the underlying type
in this case. However, we can do better.

## Solution

Add the `LoadContext::get_handle_untyped` method to get untyped handles
to assets.
This commit is contained in:
Gino Valente 2023-04-25 12:32:34 -07:00 committed by GitHub
parent 949487d92c
commit 6df65a2aa8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,6 +1,6 @@
use crate::{
path::AssetPath, AssetIo, AssetIoError, AssetMeta, AssetServer, Assets, Handle, HandleId,
RefChangeChannel,
HandleUntyped, RefChangeChannel,
};
use anyhow::Error;
use anyhow::Result;
@ -166,11 +166,16 @@ impl<'a> LoadContext<'a> {
self.get_handle(AssetPath::new_ref(self.path(), Some(label)))
}
/// Gets a handle to an asset of type `T` from its id.
/// Gets a strong handle to an asset of type `T` from its id.
pub fn get_handle<I: Into<HandleId>, T: Asset>(&self, id: I) -> Handle<T> {
Handle::strong(id.into(), self.ref_change_channel.sender.clone())
}
/// Gets an untyped strong handle for an asset with the provided id.
pub fn get_handle_untyped<I: Into<HandleId>>(&self, id: I) -> HandleUntyped {
HandleUntyped::strong(id.into(), self.ref_change_channel.sender.clone())
}
/// Reads the contents of the file at the specified path through the [`AssetIo`] associated
/// with this context.
pub async fn read_asset_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Vec<u8>, AssetIoError> {