Skip to content

Commit

Permalink
impl From<&AssetPath> for HandleId (#9132)
Browse files Browse the repository at this point in the history
# Objective

In
[`AssetLoader::load()`](https://docs.rs/bevy/0.11.0/bevy/asset/trait.AssetLoader.html#tymethod.load),
I have an
[`AssetPath`](https://docs.rs/bevy/0.11.0/bevy/asset/struct.AssetPath.html)
to a dependency asset.
I get a handle to this dependency asset using
[`LoadContext::get_handle()`](https://docs.rs/bevy/0.11.0/bevy/asset/struct.LoadContext.html#method.get_handle)
passing the `AssetPath`. But I also need to pass this `AssetPath` to
[`LoadedAsset::with_dependency()`](https://docs.rs/bevy/0.11.0/bevy/asset/struct.LoadedAsset.html#method.with_dependency)
later.


The current solution for this problem is either use `clone()`, but
`AssetPath` may contains owned data.
```rust
let dependency_path: AssetPath = _;
let dependency = load_context.get_handle(dependency_path.clone());
// ...
load_context.set_default_asset(LoadedAsset::new(my_asset).with_dependency(dependency_path));
```

Or to use `AssetPathId::from(&path)` which is a bit verbose.
```rust
let dependency_path: AssetPath = _;
let dependency = load_context.get_handle(AssetPathId::from(&dependency_path));
// ...
load_context.set_default_asset(LoadedAsset::new(my_asset).with_dependency(dependency_path));
```

Ideal solution (introduced by this PR) is to pass a reference to
`get_handle()`.
```rust
let dependency_path: AssetPath = _;
let dependency = load_context.get_handle(&dependency_path);
// ...
load_context.set_default_asset(LoadedAsset::new(my_asset).with_dependency(dependency_path));
```

## Solution

Implement `From<&AssetPath>` for `HandleId`

---

## Changelog

- Added: `HandleId` can be build from a reference to `AssetPath`.
  • Loading branch information
tguichaoua authored Jul 15, 2023
1 parent 7154b59 commit a30da00
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions crates/bevy_asset/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ impl<'a> From<AssetPath<'a>> for HandleId {
}
}

impl<'a, 'b> From<&'a AssetPath<'b>> for HandleId {
fn from(value: &'a AssetPath<'b>) -> Self {
HandleId::AssetPathId(AssetPathId::from(value))
}
}

impl HandleId {
/// Creates a random id for an asset of type `T`.
#[inline]
Expand Down

0 comments on commit a30da00

Please sign in to comment.