using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
public class DownLoad : MonoBehaviour
{
IEnumerator Start()
{
//資源包路徑
string path1 = "AssetBundles/cubewall.unity3d";
//共享依賴資源包路徑
string path2 = "AssetBundles/share.unity3d";
//第一種加載AB的方式 ,從內存中加載 LoadFromMemory
#region
//方法一:異步加載
//加載資源
AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path1));
yield return request;
//加載共同依賴資源,如貼圖、材質
AssetBundleCreateRequest request2 = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path2));
yield return request2;
AssetBundle ab = request.assetBundle;
AssetBundle ab2 = request2.assetBundle;
//使用里面的資源
GameObject wallPrefab1 = (GameObject) ab.LoadAsset("CubeWall");
Instantiate(wallPrefab1);
//方法二:同步加載(無需用協程)
//加載資源
AssetBundle ab3 = AssetBundle.LoadFromMemory(File.ReadAllBytes(path1));
//加載共同依賴資源,如貼圖、材質
AssetBundle ab4 = AssetBundle.LoadFromMemory(File.ReadAllBytes(path2));
//使用里面的資源
GameObject wallPrefab2 = (GameObject) ab.LoadAsset("CubeWall");
Instantiate(wallPrefab2);
#endregion
//第二種加載AB的方式 ,從本地加載 LoadFromFile(無需用協程)
#region
AssetBundle ab5 = AssetBundle.LoadFromFile(path1);
AssetBundle ab6 = AssetBundle.LoadFromFile(path2);
GameObject wallPrefab3 = (GameObject) ab5.LoadAsset("CubeWall");
Instantiate(wallPrefab3);
#endregion
//第三種加載AB的方式 ,從本地或服務器加載 WWW(將被棄用)
#region
//是否准備好
while (Caching.ready == false)
{
yield return null;
}
//從本地加載
//WWW www = WWW.LoadFromCacheOrDownload(@"file:/E:AssetBundleProject\AssetBundleProject\AssetBundles", 1);
//從服務器加載
WWW www = WWW.LoadFromCacheOrDownload(@"http://localhost/AssetBundles/cubewall.unity3d", 1);
yield return www;
//是否報錯
if (string.IsNullOrEmpty(www.error) == false)
{
Debug.Log(www.error);
yield break;
}
AssetBundle ab7 = www.assetBundle;
//使用里面的資源
GameObject wallPrefab4 = (GameObject) ab7.LoadAsset("CubeWall");
Instantiate(wallPrefab4);
#endregion
//第四種加載AB方式 從服務器端下載 UnityWebRequest(新版Unity使用)
#region
//服務器路徑 localhost為IP
string uri = @"http://localhost/AssetBundles/cubewall.unity3d";
UnityWebRequest request3 = UnityWebRequest.GetAssetBundle(uri);
yield return request3.Send();
//AssetBundle ab8 = ((DownloadHandlerAssetBundle)request3.downloadHandler).assetBundle;
AssetBundle ab8 = DownloadHandlerAssetBundle.GetContent(request3);
//使用里面的資源
GameObject wallPrefab5 = (GameObject) ab8.LoadAsset("CubeWall");
Instantiate(wallPrefab5);
//加載cubewall.unity3d資源包所依賴的資源包
AssetBundle manifestAB = AssetBundle.LoadFromFile("AssetBundles/AssetBundles");
AssetBundleManifest manifest = (AssetBundleManifest) manifestAB.LoadAsset("AssetBundleManifest");
//foreach(string name in manifest.GetAllAssetBundles())
//{
// print(name);
//}
//cubewall.unity3d資源包所依賴的資源包的名字
string[] strs = manifest.GetAllDependencies("cubewall.unity3d");
foreach (string name in strs)
{
AssetBundle.LoadFromFile("AssetBundles/" + name);
}
#endregion
}
}