1. 程式人生 > >使用UnityWebRequest載入AssetBundle,進行快取的方法

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

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中搜索,找到以下結果。

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;
        }
    }
}

沒有什麼好解釋的,有需要的話,直接複製以上程式碼。