Unity -- AssetBundle(本地資源加載和加載依賴關系)


1.本地資源加載

1).建立Editor文件夾

2).建立StreamingAssets文件夾和其Windows的子文件夾

將下方第一個腳本放入Editor 里面

腳本一  資源打包AssetBundle的所有標簽資源

using UnityEngine; using UnityEditor; public class Tools { [MenuItem("Tools/buildAB")] //編輯器擴展
    public static void Building() { Debug.LogError("111"); string _adPath = Application.streamingAssetsPath + "\\Windows";//路徑
 BuildPipeline.BuildAssetBundles(_adPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneLinux64);  //自動檢測有AssetBundle標簽的預制體,並進行資源壓縮. //固定格式
 } }

 

資源加載

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Load2 : MonoBehaviour { // Use this for initialization
    void Start () { //本地必須加入 file:// 這樣子www才能進行訪問
        string _abpath ="file://" +Application.streamingAssetsPath + "/Windows/sp"; StartCoroutine("Creat",_abpath); } // Update is called once per frame
    void Update () { } IEnumerator Creat(string path) { using (WWW lo=new WWW(path)) { yield return lo; if (lo != null) { AssetBundle ab = lo.assetBundle; if (ab != null) { GameObject obj = ab.LoadAsset<GameObject>("Cube"); Instantiate(obj); } } else { Debug.LogError("加載失敗"); } } }

2.加載依賴關系

using System.Collections; using System.Collections.Generic; using UnityEngine; public class LoadManCtr : MonoBehaviour { // Use this for initialization
    public string ABName; string _abPath; string _manpath; private List<AssetBundle> ManListAB; void Start () { ManListAB = new List<AssetBundle>(); _abPath = Application.streamingAssetsPath + "/Windows/"; _manpath = Application.streamingAssetsPath + "/Windows/Windows"; //查找依賴關系
        #region 加載依賴 AssetBundle _manAB = AssetBundle.LoadFromFile(_manpath); //固定格式
        AssetBundleManifest manifest = _manAB.LoadAsset<AssetBundleManifest>("AssetBundleManifest");  string[] dependencies = manifest.GetAllDependencies(ABName); Debug.LogError(dependencies.Length); //加載依賴
        if (dependencies.Length != 0) { foreach (string s in dependencies) { Debug.Log(s); //挨個加載依賴關系
                ManListAB.Add(LoadABByName(s)); //存在內存中
 } } #endregion
        //依賴加載完畢 圓柱 立方體
        AssetBundle _ab = AssetBundle.LoadFromFile(_abPath + ABName); GameObject copyObj = _ab.LoadAsset<GameObject>("Capsule"); Instantiate(copyObj); //釋放ab依賴的內存
        foreach (var v in ManListAB) { v.Unload(false); } _ab.Unload(false);//不從場景里面刪除 //true 場景刪除
        AssetBundle _ab01 = AssetBundle.LoadFromFile(_abPath + ABName);//_ab.Unload(false); 沒有這句話會重復加載
        GameObject copyObj01 = _ab01.LoadAsset<GameObject>("Capsule"); Instantiate(copyObj01,Vector3.one,Quaternion.identity); } // Update is called once per frame
    void Update () { } private AssetBundle LoadABByName(string name) { return AssetBundle.LoadFromFile(_abPath + name); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM