using System; using UnityEngine; namespace Chernobyl.Unity.Asset { /// /// Utility and extension methods for . /// public static class AssetBundleExt { /// /// Returns a that performs the same function as /// . /// public static Lazy LazyLoadFromFile(string path) => new Lazy(() => AssetBundle.LoadFromFile(path)); /// /// Performs the same function as but only if the /// has been created. /// public static void Unload(this Lazy assetBundle, bool unloadAllLoadedObjects) { if (assetBundle.IsValueCreated) assetBundle.Value.Unload(unloadAllLoadedObjects); } /// /// Same as but throws an exception if /// nothing is loaded. /// public static T LoadRequiredAsset(this AssetBundle bundle, string name) where T : UnityEngine.Object { var asset = bundle.LoadAsset(name); if (asset == null) throw new LoadAssetException(name, bundle); return asset; } /// /// Same as but throws an exception if /// nothing is loaded. /// public static Lazy LoadRequiredAsset(this Lazy bundle, string name) where T : UnityEngine.Object => new Lazy(() => bundle.Value.LoadRequiredAsset(name)); } /// /// Thrown when an asset could not be loaded from an . /// public class LoadAssetException : Exception { /// Name of the asset being loaded. /// The instance that the asset was loaded from. public LoadAssetException(string assetName, AssetBundle assetBundle) : base($"Failed to find the asset '{assetName}' in AssetBundle '{assetBundle.name}'.") { } } }