Unity5.5 AssetBundle用法-面向Android平臺(1)

3D恐龍VRAuthor發表於2018-07-15

一個AssetBundle在unity5.5中使用的例子,目標平臺是android

以一個膠囊體為例:

1、建立prefab。簡單一點,把膠囊體直接放在Assets根目錄下:

2、為prefab命名。本例中命名為cab:

3、在Assets同級路徑下建立AssetBundle根目錄。本例中目錄名稱為“AssetBundles”。

4、編寫生成AssetBundle的程式碼。程式碼如下,在Assets目錄下建立Editor資料夾,放在裡面:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class BuildAssetBundle{

	[MenuItem("AssetBundle/Build All AssetBundle")]
	static void BuildAllAssetBundle() {

		string path = "AssetBundles";//相對目錄,和Asset同級
		if (!Directory.Exists(path)) {
			Directory.CreateDirectory(path);
		}

		BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.Android);
		//None使用LZMA演算法壓縮,被壓縮的包相比LZ4更多,但是解壓時間更久,載入時間更久,解壓是必須整體解壓
		//ChunkBasedCompressor LZ4壓縮 可以指定載入具體的資源而無需全部解壓
	}
}

5、Unity主介面中,點選“AssetBundle/Build All AssetBundle”,生成AssetBundle檔案,開啟如下:

 

6、將AssetBundles資料夾拷貝至你網站的根目錄下:

7、載入資源,程式碼如下:

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class MyBehaviour : MonoBehaviour
{
	void Start()
	{
		
	}
	void OnGUI(){
		if (GUILayout.Button ("begin",GUILayout.Width(500),GUILayout.Height(300))) {
			StartCoroutine(WebRequest());
		}
	}	

	IEnumerator WebRequest() {
		string cubeURL = "http://XXX.com/yourweb/AssetBundles/cab";

		UnityWebRequest request = UnityWebRequest.GetAssetBundle(cubeURL);
		yield return request.Send();//傳送http請求

		if(string.IsNullOrEmpty(request.error)){//沒有錯誤
			AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
			GameObject cubeWall = ab.LoadAsset<GameObject>("Capsule");//獲取prefab
			Instantiate(cubeWall, Vector3.zero, Quaternion.identity);//例項化prefab
		}else{
			yield break;
		}
	}
}

8、將該指令碼繫結在場景中的物件上,執行,點選“begin”,你會發現可以正常載入資源並在零點建立了一個膠囊體物件。

 

 

 

 

 

 

 

相關文章