Unity AssetBundles打包和載入
阿新 • • 發佈:2018-11-11
一、文章詳解:AssetBundle的打包和載入
二、搭建場景
圖片右下角,根據名稱來打包,相同名字的打在同一個包裡面。專案地址
打包要求:
“picture.pa”資訊裡面打包的資訊名要記好,等到載入的時候,需用到。
注:“picture.pa”我為了看裡面的內容先放到Resources資料夾下,等看完資訊,需把它放回StreamingAssets檔案下
二、指令碼
1.打包指令碼
打包指令碼需放在Editor檔名下,自己選擇打包好放在哪個路徑下面。根據需求可以更改打包平臺Android或者IOS等等(BuildTarget.Android)。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class CreateAssetBundles : Editor { [MenuItem("Tools/Build AssetBundles")] static void BuildAllAssetBundles() { BuildPipeline.BuildAssetBundles(Application.dataPath+ "/StreamingAssets",BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.Android); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); Debug.LogWarning("打包成功"); } }
2.載入指令碼
載入資源的時候,注意名稱是否寫對,圖片要注意格式。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Test2 : MonoBehaviour { public static string BundleURL; private GameObject g; public Image image; public Image prefabPicture; private void Awake() { //平臺預處理 BundleURL = #if UNITY_ANDROID "jar:file://" + Application.dataPath + "!/assets/"; #elif UNITY_IPHONE Application.dataPath + "/Raw/"; #elif UNITY_STANDALONE_WIN || UNITY_EDITOR "file://" + Application.dataPath + "/StreamingAssets/";//Test_AssetBundle 資源束檔案的位置 #else string.Empty; #endif } public void OnPicture() { //圖片打包載入 StartCoroutine(DownLoadAssetAndScene(BundleURL + "cai.pa")); } public void OnPrefab() { //預製體打包載入 StartCoroutine(DownPrefabAndScene(BundleURL + "picture.pa")); } IEnumerator DownLoadAssetAndScene(string path) { //載入 WWW asset = new WWW(path); yield return asset; AssetBundle bundle = asset.assetBundle; //資源載入 //載入的是打包到資源包裡面,每個資源的名字 //g = Instantiate(bundle.LoadAsset("GameObject.prefab")) as GameObject; image.gameObject.SetActive(true); for (int i = 0; i < 92; i++) { image.sprite = bundle.LoadAsset<Sprite>(i + ".png");//"Resources" + yield return new WaitForSeconds(0.11f); } image.gameObject.SetActive(false); //資源載入完畢後記得Unload,不然再次載入資源的時候無法載入 bundle.Unload(false); } IEnumerator DownPrefabAndScene(string path) { //載入 WWW asset = new WWW(path); yield return asset; AssetBundle bundle = asset.assetBundle; //資源載入 //載入的是打包到資源包裡面,每個資源的名字 g = Instantiate(bundle.LoadAsset("Picture.prefab")) as GameObject; prefabPicture.gameObject.SetActive(true); for (int i = 0; i < g.GetComponent<PictureControl>().LuoShen_1.Length; i++) { prefabPicture.sprite = g.GetComponent<PictureControl>().LuoShen_1[i]; yield return new WaitForSeconds(0.11f); } //資源載入完畢後記得Unload,不然再次載入資源的時候無法載入 prefabPicture.gameObject.SetActive(false); bundle.Unload(false); } }