Created
May 15, 2024 19:56
-
-
Save tliron/55eacbfb85d4d7697de3dff3865d5a5d to your computer and use it in GitHub Desktop.
Bevy AssetReference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use bevy::asset::{io::*, *}; | |
use serde::*; | |
use tracing::*; | |
/// A serializable reference to an asset based on its path. It can only work for | |
/// assets that have paths. | |
/// | |
/// A common use case is to refer to an asset in settings for an [AssetLoader], | |
/// which must be serializable. | |
/// | |
/// The implementation is based on storing the asset's [AssetPath] components as | |
/// strings. | |
#[derive(Clone, Debug, Serialize, Deserialize)] | |
pub struct AssetReference { | |
path: String, | |
source: String, | |
} | |
impl AssetReference { | |
/// Creates an asset reference for a [Handle] that has a stringable path. | |
/// It can only work for strong handles. | |
pub fn from_handle<A: Asset>(handle: &Handle<A>) -> Option<Self> { | |
match handle.path() { | |
Some(path) => Self::from_asset_path(path), | |
None => { | |
error!("invalid handle for asset reference: {:?}", handle); | |
None | |
} | |
} | |
} | |
/// Create an asset reference from an [AssetPath] if its path and source are | |
/// stringable. | |
pub fn from_asset_path(asset_path: &AssetPath) -> Option<Self> { | |
let path = asset_path.path(); | |
match path.to_str() { | |
Some(path) => { | |
let source = asset_path.source(); | |
match source.as_str() { | |
Some(source) => Some(Self { | |
path: path.into(), | |
source: source.into(), | |
}), | |
None => { | |
error!("invalid source for asset reference: {:?}", source); | |
None | |
} | |
} | |
} | |
None => { | |
error!("invalid path for asset reference: {:?}", path); | |
None | |
} | |
} | |
} | |
/// Convert to a [Handle] if the stored path is valid. | |
pub fn as_handle<A: Asset>(&self, asset_server: &AssetServer) -> Option<Handle<A>> { | |
asset_server.get_handle(self.as_asset_path()) | |
} | |
/// Convert to an [AssetPath]. | |
pub fn as_asset_path(&self) -> AssetPath { | |
AssetPath::parse(&*self.path).with_source(AssetSourceId::from(self.source.clone())) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See Reddit discussion.