当前位置:   article > 正文

Unity3D - 使用UnityWebRequest加载AssetBundle和Texture,进行缓存的方法_unitywebrequestassetbundle 会自动做缓存吗

unitywebrequestassetbundle 会自动做缓存吗

中间有误!

暂存一些链接: https://blog.csdn.net/qq_15267341/article/details/76803416

最后补充了一些我自己写的缓存代码, 思路是先把资源包下载到本地, 在用UnityWebRequest从本地加载, 这种方法的前提是各资源包独立, 没有关联关系.

==================

最近有需求,对下载的AssetBundle进行缓存。Uniy 3D中提供的WWW.LoadFromCacheOrDownload这种自动缓存AssetBundle的类已经被标记为过时的了, 官方推荐使用UnityWebRequest类来下载资源包, 但是在网上找了好久也没发现使用这种方法如何缓存资源包.

某次看UnityWebRequest的文档的过程中发现, 下载资源包之后, 使用DownloadHandlerAssetBundle.assetBundle来加载资源包, 可以达到的AssetBundle.LoadFromFile的效率。参见下面的引用。

UnityWebRequest

You can also use the assetBundle property on the DownloadHandlerAssetBundle class after downloading the bundle to load the AssetBundle with the efficiency of AssetBundle.LoadFromFile.

 接着阅读DownloadHandlerAssetBundle的文档。这是一个DownloadHandler的子类,专门用来下载资源包的。这个子类使下载的数据变成流,输送到资源包编码和解压程序中。为资源包对象提供高效的下载和处理。

DownloadHandlerAssetBundle

Description

DownloadHandler subclass specialized for downloading AssetBundles.

This subclass streams downloaded data into Unity's asset bundle decompression and decoding system on worker threads, providing efficient downloading and processing for AssetBundle objects.

 本文结论:经过在Unity Manual中搜索,找到以下结果。

(引用自Creating DownloadHandlers, 章节:DownloadHandlerAssetBundle

DownloadHandlerAssetBundle

The advantage to this specialized Download Handler is that it is capable of streaming data to Unity’s AssetBundle system. Once the AssetBundle system has received enough data, the AssetBundle is available as a UnityEngine.AssetBundle object. Only one copy of the UnityEngine.AssetBundle object is created. This considerably reduces run-time memory allocation as well as the memory impact of loading your AssetBundle. It also allows AssetBundles to be partially used while not fully downloaded, so you can stream Assets.

All downloading and decompression occurs on worker threads.

AssetBundles are downloaded via a DownloadHandlerAssetBundle object, which has a special assetBundle property to retrieve the AssetBundle.

Due to the way the AssetBundle system works, all AssetBundle must have an address associated with them. Generally, this is the nominal URL at which they’re located (meaning the URL before any redirects). In almost all cases, you should pass in the same URL as you passed to the UnityWebRequest. When using the High Level API (HLAPI), this is done for you.

Example

  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using System.Collections;
  4. class MyBehaviour: MonoBehaviour {
  5. void Start() {
  6. StartCoroutine(GetAssetBundle());
  7. }
  8. IEnumerator GetAssetBundle() {
  9. UnityWebRequest www = new UnityWebRequest("http://www.my-server.com");
  10. DownloadHandlerAssetBundle handler = new DownloadHandlerAssetBundle(www.url, uint.MaxValue);
  11. www.downloadHandler = handler;
  12. yield return www.Send();
  13. if(www.isError) {
  14. Debug.Log(www.error);
  15. }
  16. else {
  17. // Extracts AssetBundle
  18. AssetBundle bundle = handler.assetBundle;
  19. }
  20. }
  21. }

没有什么好解释的,有需要的话,直接复制以上代码。 

在同一个文章中,还有缓存Texture的方法,在这里也一并拷贝过来收藏。

我大概解释一下下面的代码:首先获取了一个Image(UI组件,没有学过UGUI的话直接在Hierarchy视图中新建UI->Image,将此脚本附加在Image上面),然后开启协程下载图片,下载完成后获取Texture对象,然后封装成Sprite对象,Image组件将其显示出来。

  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Networking;
  4. using System.Collections;
  5. [RequireComponent(typeof(UnityEngine.UI.Image))]
  6. public class ImageDownloader : MonoBehaviour {
  7. UnityEngine.UI.Image _img;
  8. void Start () {
  9. _img = GetComponent<UnityEngine.UI.Image>();
  10. Download("http://www.mysite.com/myimage.png");
  11. }
  12. public void Download(string url) {
  13. StartCoroutine(LoadFromWeb(url));
  14. }
  15. IEnumerator LoadFromWeb(string url)
  16. {
  17. UnityWebRequest wr = new UnityWebRequest(url);
  18. DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
  19. wr.downloadHandler = texDl;
  20. yield return wr.Send();
  21. if(!wr.isError) {
  22. Texture2D t = texDl.texture;
  23. Sprite s = Sprite.Create(t, new Rect(0, 0, t.width, t.height),
  24. Vector2.zero, 1f);
  25. _img.sprite = s;
  26. }
  27. }
  28. }

 ===================================

自己写的代码

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using System.IO;
  6. using System.Text;
  7. using UnityEngine.Networking;
  8. public class LocalAssetBundleManager : MonoBehaviour {
  9. public static LocalAssetBundleManager _instance;
  10. private LinkedList<AssetItem> assetList = new LinkedList<AssetItem>();
  11. private string assetFolder;
  12. private string assetFolderForInternet;
  13. private string recordFile;
  14. private bool flag_DownloadModel;
  15. private bool flag_LoadModelFromLocal;
  16. private bool flag_LoadModelFromInternet;
  17. public bool flag_GetModel;
  18. void Awake() {
  19. _instance = this;
  20. assetFolder = Application.persistentDataPath + "/assets";
  21. assetFolderForInternet = Config.baseFolderForInternet + "/assets";
  22. Debug.Log("资源包文件夹: " + assetFolder);
  23. if (!Directory.Exists(assetFolder)) {
  24. Directory.CreateDirectory(assetFolder);
  25. }
  26. recordFile = assetFolder + "/manifest.dat";
  27. }
  28. void Start() {
  29. ReadAssetListFromFile();
  30. }
  31. void Update() {
  32. }
  33. public AssetBundle bundle;
  34. /// <summary>
  35. /// 程序入口
  36. /// </summary>
  37. /// <param name="assetBundleName">资源包路径,至少有两段如"book1/cube002/cube"</param>
  38. /// <param name="id"></param>
  39. /// <param name="version">想要的版本号(一定是最新的)</param>
  40. /// <returns></returns>
  41. public IEnumerator GetModel(string assetBundleName, int id, int version) {
  42. // 查找ID是否存在于本地的AssetList中
  43. AssetItem theAsset = null;
  44. foreach (AssetItem item in assetList) {
  45. if (item.id == id) {
  46. theAsset = item;
  47. break;
  48. }
  49. }
  50. if (theAsset != null) { // 若ID存在
  51. Debug.Log("本地存在" + assetBundleName);
  52. // 请求本资源的最新版本号
  53. if (version > theAsset.version || !theAsset.file.Equals(assetBundleName)) {
  54. // 版本号不够新 先下载模型到本地, 在从本地加载模型 TODO 需要检测错误
  55. yield return DownloadModel(assetBundleName);
  56. yield return LoadModelFromLocal(assetBundleName);
  57. if (!flag_LoadModelFromLocal) { // 如果从本地加载失败就从网络上下载
  58. yield return LoadModelFromInternet(assetBundleName);
  59. }
  60. // 更新版本号
  61. theAsset.version = version;
  62. theAsset.file = assetBundleName;
  63. SaveAssetListToFile();
  64. theAsset.assetbundle = bundle;
  65. } else {
  66. // 版本号足够, 尝试从本地加载
  67. yield return LoadModelFromLocal(assetBundleName);
  68. if (!flag_LoadModelFromLocal) {
  69. yield return LoadModelFromInternet(assetBundleName);
  70. }
  71. theAsset.assetbundle = bundle;
  72. }
  73. } else {
  74. Debug.Log("本地不存在" + assetBundleName);
  75. // 版本号不够新 先下载模型到本地, 在从本地加载模型 TODO 需要检测错误
  76. yield return DownloadModel(assetBundleName);
  77. yield return LoadModelFromLocal(assetBundleName);
  78. // 将该模型保存到资源列表
  79. if (flag_LoadModelFromLocal) {
  80. AssetItem assetItem = new AssetItem();
  81. assetItem.version = version;
  82. assetItem.id = id;
  83. assetItem.file = assetBundleName;
  84. assetList.AddLast(assetItem);
  85. SaveAssetListToFile();
  86. assetItem.assetbundle = bundle;
  87. }
  88. }
  89. }
  90. /// <summary>
  91. /// 创建文件夹并下载四个文件
  92. /// </summary>
  93. /// <param name="assetsBundleName"></param>
  94. /// <returns></returns>
  95. private IEnumerator DownloadModel(string assetsBundleName) {
  96. Debug.Log("正在从网络上下载模型文件(尚未加载)");
  97. Config.Toast("正在从网络上下载模型文件(尚未加载)");
  98. flag_DownloadModel = false;
  99. string book_cube10278; // 以样例字符串来命名变量
  100. string cube;
  101. GetLastTwoPaths(assetsBundleName, out book_cube10278, out cube);
  102. // 创建文件夹
  103. Debug.Log("即将创建文件夹 " + assetFolder + "/" + book_cube10278);
  104. if (!Directory.Exists(assetFolder + "/" + book_cube10278)) {
  105. Directory.CreateDirectory(assetFolder + "/" + book_cube10278);
  106. }
  107. // 下载第一个文件 book1/cube10278
  108. string from1 = Config.baseURL + "/AssetBundles/Android/" + book_cube10278 + "/" + GetLastPartOfPath(book_cube10278);
  109. string to1 = assetFolder + "/" + book_cube10278 + "/" + GetLastPartOfPath(book_cube10278);
  110. Debug.Log("正在下载" + from1 + "到" + to1);
  111. yield return DownloadFile(from1, to1);
  112. // 下载第二个文件 book1/cube10278.manifest
  113. string from2 = Config.baseURL + "/AssetBundles/Android/" + book_cube10278 + "/" + GetLastPartOfPath(book_cube10278) + ".manifest";
  114. string to2 = assetFolder + "/" + book_cube10278 + "/" + GetLastPartOfPath(book_cube10278) + ".manifest";
  115. Debug.Log("正在下载" + from2 + "到" + to2);
  116. yield return DownloadFile(from2, to2);
  117. // 下载第三个文件 book1/cube
  118. string from3 = Config.baseURL + "/AssetBundles/Android/" + book_cube10278 + "/" + cube;
  119. string to3 = assetFolder + "/" + book_cube10278 + "/" + cube;
  120. Debug.Log("正在下载" + from3 + "到" + to3);
  121. yield return DownloadFile(from3, to3);
  122. // 下载第四个文件 book1/cube.manifest
  123. string from4 = Config.baseURL + "/AssetBundles/Android/" + book_cube10278 + "/" + cube + ".manifest";
  124. string to4 = assetFolder + "/" + book_cube10278 + "/" + cube + ".manifest";
  125. Debug.Log("正在下载" + from4 + "到" + to4);
  126. yield return DownloadFile(from4, to4);
  127. flag_DownloadModel = true;
  128. }
  129. /// <summary>
  130. /// 从Internet路径上下载文件, 存入Local文件中
  131. /// </summary>
  132. /// <param name="internet"></param>
  133. /// <param name="local"></param>
  134. /// <returns></returns>
  135. private IEnumerator DownloadFile(string internet, string local) {
  136. WWW www = new WWW(internet);
  137. yield return www;
  138. File.WriteAllBytes(local, www.bytes);
  139. }
  140. /// <summary>
  141. /// 从本地加载模型
  142. /// </summary>
  143. /// <param name="assetBundleName"></param>
  144. /// <returns></returns>
  145. private IEnumerator LoadModelFromLocal(string assetBundleName) {
  146. flag_LoadModelFromLocal = false;
  147. string uri = assetFolderForInternet + "/" + assetBundleName;
  148. Debug.Log("正在从本地加载模型: " + uri);
  149. UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri, 0);
  150. Config.Toast("从本地加载模型" + uri);
  151. yield return request.Send(); // 任务: 抛出异常如何处理?
  152. try {
  153. Debug.Log(String.Format("本地模型{0}加载完成", assetBundleName));
  154. bundle = DownloadHandlerAssetBundle.GetContent(request);
  155. // GameObject obj = bundle.LoadAsset<GameObject>(GetLastPartOfPath(assetBundleName) + ".prefab");
  156. flag_LoadModelFromLocal = true;
  157. } catch (Exception e) {
  158. Debug.Log(e.Message);
  159. flag_LoadModelFromLocal = true;
  160. }
  161. }
  162. /// <summary>
  163. /// 从网上下载模型
  164. /// </summary>
  165. /// <param name="assetBundleName"></param>
  166. /// <returns></returns>
  167. private IEnumerator LoadModelFromInternet(string assetBundleName) {
  168. flag_LoadModelFromInternet = false;
  169. string uri = Config.baseURL + "/AssetBundles/Android/" + assetBundleName;
  170. Config.Toast("缓存不足, 直接从网络上下载并使用");
  171. UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri, 0);
  172. yield return request.Send(); // 任务: 抛出异常如何处理?
  173. try {
  174. bundle = DownloadHandlerAssetBundle.GetContent(request);
  175. GameObject obj = bundle.LoadAsset<GameObject>(GetLastPartOfPath(assetBundleName) + ".prefab");
  176. Debug.Log(String.Format("模型{0}下载完成", assetBundleName));
  177. flag_LoadModelFromInternet = true;
  178. } catch (Exception e) {
  179. Debug.Log(e.Message);
  180. flag_LoadModelFromInternet = true;
  181. }
  182. }
  183. /// <summary>
  184. /// 从文件读取资源列表
  185. /// </summary>
  186. private void ReadAssetListFromFile() {
  187. if (File.Exists(recordFile)) {
  188. string json = File.ReadAllText(recordFile);
  189. try {
  190. Assets assets = JsonUtility.FromJson<Assets>(json);
  191. assetList.Clear();
  192. for (int i = 0; i < assets.assets.Length; i++) {
  193. assetList.AddLast(assets.assets[i]);
  194. }
  195. } catch {
  196. assetList.Clear();
  197. }
  198. } else {
  199. assetList.Clear();
  200. }
  201. }
  202. /// <summary>
  203. /// 将资源列表保存到文件
  204. /// </summary>
  205. private void SaveAssetListToFile() {
  206. StringBuilder sb = new StringBuilder();
  207. sb.Append("{\"assets\":[");
  208. foreach (AssetItem item in assetList) {
  209. sb.Append(item.ToString());
  210. sb.Append(',');
  211. }
  212. if (assetList.Count > 0) {
  213. sb.Remove(sb.Length - 1, 1); // 删除最后一个逗号
  214. }
  215. sb.Append("]}");
  216. File.WriteAllText(recordFile, sb.ToString());
  217. }
  218. public void GetLastTwoPaths(string route, out string penultimate, out string last) {
  219. string[] strs = route.Split('/');
  220. last = strs[strs.Length - 1];
  221. penultimate = route.Substring(0, route.Length - last.Length - 1);
  222. }
  223. public static String GetLastPartOfPath(string route) {
  224. string[] strs = route.Split('/');
  225. return strs[strs.Length - 1];
  226. }
  227. }
  228. [Serializable]
  229. public class Assets {
  230. public AssetItem[] assets;
  231. }
  232. [Serializable]
  233. public class AssetItem {
  234. public int id;
  235. public string file;
  236. public int version;
  237. public AssetBundle assetbundle; // 本变量只是引用加载内存中的资源包
  238. public override String ToString() {
  239. return String.Format("{{\"id\":{0},\"file\":\"{1}\",\"version\":{2}}}", id, file, version);
  240. }
  241. }

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号