使用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

using UnityEngine;
using UnityEngine.Networking; 
using System.Collections;
 
class MyBehaviour: MonoBehaviour {
    void Start() {
        StartCoroutine(GetAssetBundle());
    }
 
    IEnumerator GetAssetBundle() {
        UnityWebRequest www = new UnityWebRequest("http://www.my-server.com");
        DownloadHandlerAssetBundle handler = new DownloadHandlerAssetBundle(www.url, uint.MaxValue);
        www.downloadHandler = handler;
        yield return www.Send();
 
        if(www.isError) {
            Debug.Log(www.error);
        }
        else {
            // Extracts AssetBundle
            AssetBundle bundle = handler.assetBundle;
        }
    }
}

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

猜你喜欢

转载自blog.csdn.net/u010099177/article/details/84229653
今日推荐