Unity打包AssetBundle

添加了AssetBundleName的文件,都會被打包到StreammingAssets。所以需要在打包前,把其他文件夾的AssetBundleName清除一下。

if (subDirs.Length == 1 && subDirs[0].Name == "Materials")  //滿足這個條件,纔會添加AsssetbundleName

 

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
//using Base.Common;

 

public class AssetbundleTool : MonoBehaviour {

    static string GetStreamingAssetsDir(){
        string targetPath = Application.dataPath + "/StreamingAssets/";
        if (!Directory.Exists (targetPath)) {
            Directory.CreateDirectory(targetPath);
        }
        return targetPath;
    }

    //[MenuItem("EditorTool/Create AssetBunldes Main")]
    //static void CreateAssetBunldesMain()
    //{
    //    //獲取在Project視圖中選擇的所有遊戲對象
    //    Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
    //    string streamingAssetDir = GetStreamingAssetsDir();
    //    //遍歷所有的遊戲對象
    //    foreach (Object obj in SelectedAsset)
    //    {
    //        string sourcePath = AssetDatabase.GetAssetPath(obj);
    //        //本地測試:建議最後將Assetbundle放在StreamingAssets文件夾下,如果沒有就創建一個,因爲移動平臺下只能讀取這個路徑
    //        //StreamingAssets是隻讀路徑,不能寫入
    //        //服務器下載:就不需要放在這裏,服務器上客戶端用www類進行下載。
    //        Debug.Log("dataPaht:" + Application.dataPath);
    //        string targetPath = streamingAssetDir + obj.name + ".assetbundle";
    //        if (BuildPipeline.BuildAssetBundle(obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies))
    //        {
    //            Debug.Log(obj.name + "資源打包成功");
    //        }
    //        else
    //        {
    //            Debug.Log(obj.name + "資源打包失敗");
    //        }
    //    }
    //    //刷新編輯器
    //    AssetDatabase.Refresh();
    //}

    //[MenuItem("EditorTool/Create AssetBunldes ALL")]
    //static void CreateAssetBunldesALL ()
    //{

    //    Caching.CleanCache ();
    //    string Path = GetStreamingAssetsDir()+"ALL.assetbundle";
    //    Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
    //    foreach (Object obj in SelectedAsset) {
    //        Debug.Log ("Create AssetBunldes name :" + obj);
    //    }
    //    //這裏注意第二個參數就行
    //    if (BuildPipeline.BuildAssetBundle (null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies)) {
    //        AssetDatabase.Refresh ();
    //    } else {
    //    }
    //}

    [MenuItem("EditorTool/Build AssetBunldes")]//創建AssetBunldeName
    static void CreateAssetBunldesMain()
    {
#if UNITY_2017 || UNITY_2018
        bool clearValue=Caching.ClearCache();
        Debug.Log("Clear cache:"+clearValue);
#else
        Caching.CleanCache();//清除緩存,才能保證每次獲取的依賴資源是最新的(方法.GetAllDependencies())
#endif
        string path = GetStreamingAssetsDir();
        BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
        AssetDatabase.Refresh();

    }

    /// <summary>
    /// 將所有文件夾內的文件打包到一個AssetBundle中
    /// 針對放模型的“文件夾”設置AssetBunldeName,文件夾可以包括模型、材質、貼圖等
    /// </summary>
    [MenuItem("EditorTool/SetDirectoryToAssetBundle")]
    static void SetDirectoryToAssetBundle()
    {
        //獲取在Project視圖中選擇的所有遊戲對象
        var dirObjs = GetDirObjs();
        if (dirObjs.Count == 0) return;//選中的沒有文件夾
        foreach (Object dirObj in dirObjs)
        {
            var dir = GetDirInfo(dirObj);
            SetFilesAssetName(dir);
        }
        CreateAssetBunldesMain();
        //刷新編輯器
        AssetDatabase.Refresh();
    }

    private static List<Object> GetDirObjs()
    {
        Object[] selectedAssets = Selection.GetFiltered(typeof (Object), SelectionMode.Assets);
        //Object[] SelectedAssetSub = Selection.GetFiltered(typeof(Object), SelectionMode.Editable);//不包括不可修改的文件,文件夾屬於不可修改的文件
        //List<Object> SelectedAssetList = new List<Object>(SelectedAsset);
        List<Object> dirObjs = new List<Object>();
        foreach (Object obj in selectedAssets)
        {
            string sourcePath = AssetDatabase.GetAssetPath(obj);
            if (Directory.Exists(sourcePath)) //判斷是否是文件夾
            {
                dirObjs.Add(obj);
            }
        }
        return dirObjs;
    }

    private static void SetFilesAssetName(DirectoryInfo dir)
    {
        FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories); //搜索文件夾下面的所有文件

        List<Object> subObjects = new List<Object>();
        Regex regex = new Regex(".(meta|cs|xml)$"); //正則表達式,過濾後綴爲.meta.cs.xml的文件
        foreach (FileInfo file in files)
        {
            string filePath = file.FullName;
            int index = filePath.IndexOf(Application.dataPath);
            string relativePath = filePath.Substring(Application.dataPath.Length + 1);
            relativePath = "Assets\\" + relativePath;
            //List<Object> subs = new List<Object>();
            //subs.Add(AssetDatabase.LoadAssetAtPath<Object>(relativePath));//如果路徑文件後綴爲.meta,則AssetDatabase.LoadAssetAtPath<Object>(relativePath)返回爲null;
            if (regex.IsMatch(relativePath))
            {
                continue;
            }
            Object subObj = AssetDatabase.LoadAssetAtPath<Object>(relativePath);
            subObjects.Add(subObj);
        }

        string assetName = dir.Name;
#if UNITY_ANDROID || UNITY_WEBGL
        //assetName = PinYinConverter.Get(assetName);
#endif

        List<string> assets=new List<string>();

        //遍歷所有的遊戲對象
        foreach (Object subObj in subObjects)
        {
            string sPath = AssetDatabase.GetAssetPath(subObj);
            //本地測試:建議最後將Assetbundle放在StreamingAssets文件夾下,如果沒有就創建一個,因爲移動平臺下只能讀取這個路徑
            //StreamingAssets是隻讀路徑,不能寫入
            //服務器下載:就不需要放在這裏,服務器上客戶端用www類進行下載。
            //Debug.Log("dataPaht:" + Application.dataPath);

            AssetImporter importer = AssetImporter.GetAtPath(sPath);
            //importer.assetBundleName = sourcePath;
            importer.assetBundleName = assetName;

            //#if UNITY_ANDROID || UNITY_WEBGL
            //            sPath = PinYinConverter.Get(sPath);
            //#endif
            assets.Add(sPath);
        }
        List<AssetBundleBuild> builds = new List<AssetBundleBuild>();
        AssetBundleBuild bundle = new AssetBundleBuild();
        bundle.assetBundleName = assetName;
        bundle.assetNames = assets.ToArray();
        builds.Add(bundle);
        string path = GetStreamingAssetsDir();

        //#if UNITY_5_3
        //        BuildPipeline.BuildAssetBundles(path, builds.ToArray());
        //        //BuildPipeline.BuildAssetBundles(path, builds.ToArray(), 0, EditorUserBuildSettings.activeBuildTarget);
        //        //#elif UNITY_5_4
        //#else
        //AssetBundleManifest manifest=BuildPipeline.BuildAssetBundles(path, builds.ToArray(), BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
        //manifest.GetAllAssetBundles()
        //#endif

    }


    private static DirectoryInfo GetDirInfo(Object dirObj)
    {
        string sourcePath = AssetDatabase.GetAssetPath(dirObj);
        DirectoryInfo dir = new DirectoryInfo(sourcePath); //獲取文件夾
        return dir;
    }

    /// <summary>
    /// 將所有文件夾內的文件打包到一個AssetBundle中
    /// SetDirectoryToAssetBundle的擴充,選中一個根目錄就能把裏面所有的有模型的文件夾單個打包
    /// </summary>
    [MenuItem("EditorTool/SetDirectoryToAssetBundleEx")]
    static void SetDirectoryToAssetBundleEx()
    {
        //獲取在Project視圖中選擇的所有遊戲對象
        var dirObjs = GetDirObjs();
        if (dirObjs.Count == 0) return;//選中的沒有文件夾
        foreach (Object dirObj in dirObjs)
        {
            var dir = GetDirInfo(dirObj);
            SetDirAssetName(dir);
        }

        CreateAssetBunldesMain();

        //刷新編輯器
        AssetDatabase.Refresh();

    }

    private static void SetDirAssetName(DirectoryInfo dir)
    {
        //Debug.Log(string.Format("SetDirAssetName:{0}",dir.FullName));
        DirectoryInfo[] subDirs = dir.GetDirectories();
        if (subDirs.Length == 1 && subDirs[0].Name == "Materials")  //滿足這個條件,纔會添加AsssetbundleName
        {
            SetFilesAssetName(dir);
        }
        else
        {
            foreach (DirectoryInfo subDir in subDirs)
            {
                SetDirAssetName(subDir);
            }
        }
    }

    /// <summary>
    /// 一個“文件”生成一個AssetBunldeName,文件可以包括模型、材質、貼圖等
    /// </summary>
    [MenuItem("EditorTool/SetFilesToAssetBundle")]
    static void SetFilesToAssetBundle()
    {
        //獲取在Project視圖中選擇的所有遊戲對象,不包括文件夾
        //Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Editable);//不包括不可修改的文件,文件夾屬於不可修改的文件

        //獲取在Project視圖中選擇的所有遊戲對象
        //Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        //Object[] SelectedAssetSub = Selection.GetFiltered(typeof(Object), SelectionMode.Editable);//不包括不可修改的文件,文件夾屬於不可修改的文件

        //List<Object> SelectedAssetList = new List<Object>(SelectedAsset);
        //return;
        List<Object> SelectedAssetSub = new List<Object>();//不包括文件夾
        //foreach (Object o in SelectedAssetSub)
        //{
        //    if (SelectedAssetList.Contains(o))
        //    {
        //        SelectedAssetList.Remove(o);
        //    }
        //}

        foreach (Object o in SelectedAsset)
        {
            string sourcePath = AssetDatabase.GetAssetPath(o);
            if (File.Exists(sourcePath))//File.Exists()判斷是否是文件,過濾文件夾
            {
                SelectedAssetSub.Add(o);
            }

        }

        if (SelectedAssetSub.Count == 0) return;//選中的沒有文件

        //遍歷所有的遊戲對象
        foreach (Object obj in SelectedAssetSub)
        {
            string sourcePath = AssetDatabase.GetAssetPath(obj);
            //本地測試:建議最後將Assetbundle放在StreamingAssets文件夾下,如果沒有就創建一個,因爲移動平臺下只能讀取這個路徑
            //StreamingAssets是隻讀路徑,不能寫入
            //服務器下載:就不需要放在這裏,服務器上客戶端用www類進行下載。
            Debug.Log("dataPaht:" + Application.dataPath);
            AssetImporter importer = AssetImporter.GetAtPath(sourcePath);
            importer.assetBundleName = obj.name;

        }
        //刷新編輯器
        AssetDatabase.Refresh();
    }

    [MenuItem("EditorTool/Clear AssetBunldesName")]//清空AssetBunldeName
    static void ClearAssetBunldesName()
    {
        //獲取在Project視圖中選擇的所有遊戲對象,不包括文件夾
        //Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Editable);//不包括不可修改的文件,文件夾屬於不可修改的文件

        //獲取在Project視圖中選擇的所有遊戲對象
        //Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        //Object[] SelectedAssetSub = Selection.GetFiltered(typeof(Object), SelectionMode.Editable);//不包括不可修改的文件,文件夾屬於不可修改的文件

        //List<Object> SelectedAssetList = new List<Object>(SelectedAsset);
        //return;
        List<Object> SelectedAssetSub = new List<Object>();//不包括文件夾
        //foreach (Object o in SelectedAssetSub)
        //{
        //    if (SelectedAssetList.Contains(o))
        //    {
        //        SelectedAssetList.Remove(o);
        //    }
        //}

        foreach (Object o in SelectedAsset)
        {
            string sourcePath = AssetDatabase.GetAssetPath(o);
            if (File.Exists(sourcePath))//File.Exists()判斷是否是文件,過濾文件夾
            {
                SelectedAssetSub.Add(o);
            }

        }

        if (SelectedAssetSub.Count == 0) return;//選中的沒有文件

        //遍歷所有的遊戲對象
        foreach (Object obj in SelectedAssetSub)
        {
            string sourcePath = AssetDatabase.GetAssetPath(obj);
            //本地測試:建議最後將Assetbundle放在StreamingAssets文件夾下,如果沒有就創建一個,因爲移動平臺下只能讀取這個路徑
            //StreamingAssets是隻讀路徑,不能寫入
            //服務器下載:就不需要放在這裏,服務器上客戶端用www類進行下載。
            //Debug.Log("dataPaht:" + Application.dataPath);
            AssetImporter importer = AssetImporter.GetAtPath(sourcePath);
            importer.assetBundleName = "";

        }
        //刷新編輯器
        AssetDatabase.Refresh();
        Debug.Log("Clear name complete...");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章