隨筆-Unity關於利用AssetBundle打包資源與加載資源

最近在作項目的時候想給工程里加一個讀取外部資源包的功能,由於是個展現類的項目,若是要增長新的產品只須要將資源打包,經過加載資源包就能夠作到不用從新build就能夠更新。這也是熱更新中的一個環節ios

 

1)首先在Asset根目錄下建立EditorStreamingAssets文件夾web

        建立C#腳本取名爲CreateAssetBundle此爲打包腳本,在Editor下執行便可,貼上代碼windows

public class AutoCreateAssetBundle : Editor
{
    const string path = "Assets/StreamingAssets/";
    [MenuItem("Tools/Build")]
    public static void BuildAssetBundle()
    {
        string outPath = path;
        if (!Directory.Exists(outPath))
        {
            Directory.CreateDirectory(outPath);
        }
        BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
        AssetDatabase.Refresh();
    }
}

 

2)接下來將須要打包的資源整理好作成預製ui

      在Priject視圖中選中須要打包的資源的預製體,設置AssetBundle的名字和文件類型spa

      

     文件類型設置爲unity3d便可3d

3)下來就能夠打包了code

        在菜單欄中選擇Tools->Buildblog

         

4)等待打包完成就會在StreamingAssets目錄下生成兩個文件ip

     

 

至此打包工做就完成了,下面是加載部分資源

將這兩個文件放入須要加載資源的工程StreamingAssets的目錄

不過多贅述了,直接上代碼

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public class LoadBuildAsset : MonoBehaviour
    {
        private string path;

        private void Awake()
        {

            path =
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
                    "file://" + Application.dataPath + "/StreamingAssets/";  //windows和web平臺
#elif UNITY_IPHONE
                    Application.dataPath + "/Raw/";                          //ios平臺
#elif UNITY_ANDROID
                    "jar:file://" + Application.dataPath + "!/assets/";      //andriod平臺
#else
                     string.Empty;
#endif
            buildName = "boxandui.unity3d";

            StartCoroutine(LoadMainGameObject(path + buildName));
        }

        /// <summary>
        /// 獲取資源
        /// </summary>
        /// <param name="_path"></param>
        /// <returns></returns>
        private IEnumerator LoadMainGameObject(string _path)
        {
            using (WWW asset = new WWW(_path))
            {
                yield return asset;
                AssetBundle ab = asset.assetBundle;
                UnityEngine.Object[] objs = ab.LoadAllAssets();
                GameObject objCache;
                foreach (var obj in objs)
                {
                    objCache = Instantiate(obj) as GameObject;
                }
                yield return new WaitForSeconds(3);
            }
        }
    }

    這裏須要注意的就是不一樣的平臺StreamingAssets的路徑是不一樣的

 

至此,利用AssetBundle打包資源及加載資源就完成了

相關文章
相關標籤/搜索