unity 异步加载网络图片_一个非常好用的AssetBundle资源加载器
Loxodon Framework Bundle是一個非常好用的AssetBundle加載器,也是一個AssetBundle冗余分析工具。它能夠自動管理AssetBundle之間復雜的依賴關系,它通過引用計數來維護AssetBundle之間的依賴。你既可以預加載一個AssetBundle,自己管理它的釋放,也可以直接通過異步的資源加載函數直接加載資源,資源加載函數會自動去查找資源所在的AB包,自動加載AB,使用完后又會自動釋放AB。 它還支持弱緩存,如果對象模板已經在緩存中,則不需要重新去打開AB。它支持多種加載方式,WWW加載,UnityWebRequest加載,File方式的加載等等(在Unity5.6以上版本,請不要使用WWW加載器,它會產生內存峰值)。它提供了一個AssetBundle的打包界面,支持加密AB包(只建議加密敏感資源,因為會影響性能)。同時它也繞開了Unity3D早期版本的一些bug,比如多個協程并發加載同一個資源,在android系統會出錯。它的冗余分析是通過解包AssetBundle進行的,這比在編輯器模式下分析的冗余更準確。
下載地址:AssetStore 下載
打包工具介紹
- 編輯打包的工具:
- 打包后的文件概要信息
- 打包后的文件
- 冗余分析工具
- 冗余分析結果
使用示例
- 初始化IResources
整個項目面向接口設計,任何組件都是可以自定義或者可選的,下圖是我默認的一個示例。
IResources- 自定義AB的查詢規則
AssetBundle資源可以存在Unity3D的緩存中,也可以存在持久化目錄中或者在StreamingAssets目錄中,關于如何存儲資源,一般和項目怎么更新資源有關系,在我的CustomBundleLoaderBuilder中,你可以自定義自己的加載規則和選擇使用自己喜歡的加載器(WWW、UnityWebRequest、File等)。
using System;using Loxodon.Framework.Bundles;namespace Loxodon.Framework.Examples.Bundle {public class CustomBundleLoaderBuilder : AbstractLoaderBuilder{private bool useCache;private IDecryptor decryptor;public CustomBundleLoaderBuilder(Uri baseUri, bool useCache) : this(baseUri, useCache, null){}public CustomBundleLoaderBuilder(Uri baseUri, bool useCache, IDecryptor decryptor) : base(baseUri){this.useCache = useCache;this.decryptor = decryptor;}public override BundleLoader Create(BundleManager manager, BundleInfo bundleInfo, BundleLoader[] dependencies){//Customize the rules for finding assets.Uri loadBaseUri = this.BaseUri; //eg: http://your ip/bundlesif (this.useCache && BundleUtil.ExistsInCache(bundleInfo)){//Load assets from the cache of Unity3d.loadBaseUri = this.BaseUri; #if UNITY_5_4_OR_NEWERreturn new UnityWebRequestBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache); #elsereturn new WWWBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache); #endif}if (BundleUtil.ExistsInStorableDirectory(bundleInfo)){//Load assets from the "Application.persistentDataPath/bundles" folder./* Path: Application.persistentDataPath + "/bundles/" + bundleInfo.Filename */loadBaseUri = new Uri(BundleUtil.GetStorableDirectory());}#if !UNITY_WEBGL || UNITY_EDITORelse if (BundleUtil.ExistsInReadOnlyDirectory(bundleInfo)){//Load assets from the "Application.streamingAssetsPath/bundles" folder./* Path: Application.streamingAssetsPath + "/bundles/" + bundleInfo.Filename */loadBaseUri = new Uri(BundleUtil.GetReadOnlyDirectory());} #endifif (bundleInfo.IsEncrypted){if (this.decryptor != null && bundleInfo.Encoding.Equals(decryptor.AlgorithmName))return new CryptographBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, decryptor);throw new NotSupportedException(string.Format("Not support the encryption algorithm '{0}'.", bundleInfo.Encoding));}//Loads assets from an Internet address if it does not exist in the local directory. #if UNITY_5_4_OR_NEWERif (this.IsRemoteUri(loadBaseUri))return new UnityWebRequestBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache);elsereturn new FileAsyncBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager); #elsereturn new WWWBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache); #endif}} }- 加載一個資源
加載資源是根據資源的路徑來加載的,如果你選擇了路徑自動映射的路徑解析器,那么通過資源的路徑,就可以自動找到所在的AssetBundle包。下面是資源加載的示例。
2.通過回調方式加載場景
void LoadSceneByCallback(string sceneName){ISceneLoadingResult<Scene> result = this.resources.LoadSceneAsync(sceneName);result.AllowSceneActivation = false;result.OnProgressCallback(p =>{//Debug.LogFormat("Loading {0}%", (p * 100));});result.OnStateChangedCallback(state =>{if (state == LoadState.Failed)Debug.LogFormat("Loads scene '{0}' failure.Error:{1}", sceneName, result.Exception);else if (state == LoadState.Completed)Debug.LogFormat("Loads scene '{0}' completed.", sceneName);else if (state == LoadState.AssetBundleLoaded)Debug.LogFormat("The AssetBundle has been loaded.");else if (state == LoadState.SceneActivationReady){Debug.LogFormat("Ready to activate the scene.");result.AllowSceneActivation = true;}});}3.通過協程的方式加載場景
IEnumerator LoadSceneByCoroutine(string sceneName){ISceneLoadingResult<Scene> result = this.resources.LoadSceneAsync(sceneName);while (!result.IsDone){//Debug.LogFormat("Loading {0}%", (result.Progress * 100));yield return null;}if (result.Exception != null){Debug.LogFormat("Loads scene '{0}' failure.Error:{1}", sceneName, result.Exception);}else{Debug.LogFormat("Loads scene '{0}' completed.", sceneName);}}- 下載示例
我提供了一個AssetBundle資源下載的示例,它通過最新版本的資源索引庫Manifest.dat ,查找本地不存在的AB資源,然后通過網絡下載本地缺失的AB資源。
IEnumerator Download(){this.downloading = true;try{IProgressResult<Progress, BundleManifest> manifestResult = this.downloader.DownloadManifest(BundleSetting.ManifestFilename);yield return manifestResult.WaitForDone();if (manifestResult.Exception != null){Debug.LogFormat("Downloads BundleManifest failure.Error:{0}", manifestResult.Exception);yield break;}BundleManifest manifest = manifestResult.Result;IProgressResult<float, List<BundleInfo>> bundlesResult = this.downloader.GetDownloadList(manifest);yield return bundlesResult.WaitForDone();List<BundleInfo> bundles = bundlesResult.Result;if (bundles == null || bundles.Count <= 0){Debug.LogFormat("Please clear cache and remove StreamingAssets,try again.");yield break;}IProgressResult<Progress, bool> downloadResult = this.downloader.DownloadBundles(bundles);downloadResult.Callbackable().OnProgressCallback(p =>{Debug.LogFormat("Downloading {0:F2}KB/{1:F2}KB {2:F3}KB/S", p.GetCompletedSize(UNIT.KB), p.GetTotalSize(UNIT.KB), p.GetSpeed(UNIT.KB));});yield return downloadResult.WaitForDone();if (downloadResult.Exception != null){Debug.LogFormat("Downloads AssetBundle failure.Error:{0}", downloadResult.Exception);yield break;}Debug.Log("OK");if (this.resources != null){//update BundleManager's manifestBundleManager manager = (this.resources as BundleResources).BundleManager as BundleManager;manager.BundleManifest = manifest;}#if UNITY_EDITORUnityEditor.EditorUtility.OpenWithDefaultApp(BundleUtil.GetStorableDirectory()); #endif}finally{this.downloading = false;}}下面是這個項目在AssetStore上的介紹
AssetBundle Manager for Unity3D
Loxodon Framework Bundle is an AssetBundle manager.It provides a functionality that can automatically manage/load an AssetBundle and its dependencies from local or remote location.Asset Dependency Management including BundleManifest that keep track of every AssetBundle and all of their dependencies. An AssetBundle Simulation Mode which allows for iterative testing of AssetBundles in a the Unity editor without ever building an AssetBundle.
The Loxodon Framework Bundle includes all the source code, it works alone, or works with the Loxodon Framework, AssetBundles-Browser.
For tutorials,examples and support,please see the project.You can also discuss the project in the Unity Forums.
Asset Redundancy Analyzer
The asset redundancy analyzer can help you find the redundant assets included in the AssetsBundles.Create a fingerprint for the asset by collecting the characteristic data of the asset. Find out the redundant assets in all AssetBundles by fingerprint comparison.it only supports the AssetBundle of Unity 5.6 or higher.
Tested in Unity 3D on the following platforms:
PC/Mac/Linux
Android
IOS
UWP(Windows 10)
WebGL
Key features:
- Support encryption and decoding of the AssetBundle files(支持AssetBundle文件的加密和解密);
- Use reference counting to manage the dependencies of AssetBundle(使用引用計數來管理AssetBundle的依賴關系);
- Automatically unloading AssetBundle with reference count 0 by destructor or "Dispose" method(當引用計數為0時,通過析構函數或者Dispose函數自動卸載AssetBundle);
- Use weak cache to optimize load performance(使用弱緩存來優化加載性能);
- Interface-oriented programming, you can customize the loader and file search rules for the AssetBundle(面向接口編程,可以自定義加載器,自定義AssetBundle的查找規則);
- Support for simulating loading in the editor without building AssetBundles(在編輯器下,支持模擬AssetBundle的方式加載資源以方便測試);
- Supports the unpacking and the redundancy analysis of the AssetBundle(支持通過AssetBundle包來分析資源冗余,這比在Editor模式分析的冗余更準確);
For More Information Contact Us at: yangpc.china@gmail.com
總結
以上是生活随笔為你收集整理的unity 异步加载网络图片_一个非常好用的AssetBundle资源加载器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python plot 坐标轴范围_Py
- 下一篇: 主线程如何等待多线程完成 返回数据_多线