Skip to content

Commit

Permalink
bevy_asset: Add LoadContext::get_handle_untyped (#8470)
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
MrGVSV authored Apr 25, 2023
1 parent 949487d commit 6df65a2
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions crates/bevy_asset/src/loader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
path::AssetPath, AssetIo, AssetIoError, AssetMeta, AssetServer, Assets, Handle, HandleId,
RefChangeChannel,
HandleUntyped, RefChangeChannel,
};
use anyhow::Error;
use anyhow::Result;
Expand Down Expand Up @@ -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> {
Expand Down

0 comments on commit 6df65a2

Please sign in to comment.