主要講Assetbundle的網絡加載方式
之前所講的都是AssetBundle.LoadFromFile的方法,這是直接從硬盤上加載,而且屬於同步加載。
WWW.LoadFromCacheOrDownload
呵呵噠,這個方法現在已經棄用了。然而我用的是5.4的版本,還是可以用的。
解釋一下方法裏的參數,第一個url就是下載的路徑,第二個version是指版本號,如果要下載的東西的版本和本地已存在的版本號一樣那就用本地,如果不一樣那就會從地址裏下載到本地。
此方法應用的代碼如下:
看完下面代碼,可能會想爲什麼要用這方法而不是 using (WWW www = new WWW(url))的方法呢? ??using (WWW www = new WWW(url))方法也是可以使用的(親測),但是官網解釋的很清楚那就是LoadFromCacheOrDownload() must be used in place of "new WWW (url)" in order to utilize caching functionality.,爲了處理緩存問題,而new WWW是不具備處理緩存的功能的。注意這個方法只能用來接收AssetBundles的文件不適合其他類型的緩存。
特別注意Note: URL must be '%' escaped. 路徑裏是不能使用%的。
using UnityEngine;
using System.Collections;
public class loadtest : MonoBehaviour {
public string url;
string PathA;
// Use this for initialization
private void Awake()
{
PathA = System.Environment.CurrentDirectory;
//因爲測試是使用的本地路徑,本地路徑的斜槓是“\”所以需要用“/”來代替
if (PathA.Contains("\\"))
{
PathA = PathA.Replace("\\", "/");
}
url = "file://" + PathA + "/AllAssets/test.assetbundle";
Debug.Log(url);
}
IEnumerator LoadAssetsFun()
{
while (!Caching.ready)
yield return null;
var www = WWW.LoadFromCacheOrDownload(url,0);
yield return www;
if (!string .IsNullOrEmpty(www.error))
{
Debug.Log(www.error);
yield return null;
}
AssetBundle myload = www.assetBundle;
if(myload==null)
{
Debug.Log("下載錯誤");
}
Object[] obj = myload.LoadAllAssets();
foreach (Object ass in obj)
{
Debug.Log(ass.name);
Instantiate(ass);
}
myload.Unload(false);
}
private void OnGUI()
{
Rect rect = new Rect(100f, 100f, 200f, 200f);
if (GUI.Button(rect, "Load"))
{
StartCoroutine(LoadAssetsFun());
}
}
}
UnityWebRequest
該方法爲新版的方法,最推薦使用它來代替www的方法,因爲該方法可以減小內存開銷。
先用UnityWebRequest.GetAssetBundle進行下載,再用DownloadHandlerAssetBundle.GetContent(UnityWebRequest)獲取AB對象
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class loadtest : MonoBehaviour {
public string url;
string PathA;
// Use this for initialization
private void Awake()
{
PathA = System.Environment.CurrentDirectory;
//因爲測試是使用的本地路徑,本地路徑的斜槓是“\”所以需要用“/”來代替
if (PathA.Contains("\\"))
{
PathA = PathA.Replace("\\", "/");
}
url = "file://" + PathA + "/AllAssets/test.assetbundle";
Debug.Log(url);
}
IEnumerator LoadAssetsFun()
{
UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.GetAssetBundle(url, 0);
yield return request.Send();
AssetBundle myload = DownloadHandlerAssetBundle.GetContent(request);
Object[] obj = myload.LoadAllAssets();
foreach (Object ass in obj)
{
Debug.Log(ass.name);
Instantiate(ass);
}
myload.Unload(false);
}
private void OnGUI()
{
Rect rect = new Rect(100f, 100f, 200f, 200f);
if (GUI.Button(rect, "Load"))
{
StartCoroutine(LoadAssetsFun());
}
}
}