Unity C# 打包AssetBundle與場景

weixin_34127717發表於2019-02-27

Unity2018已經把打包過程簡化很多了
我們只需要關心兩個API:
1.BuildPipline.BuildAssetBundles() 打包AssetBundle
2.BuildPipline.BuildPlayer() 打包場景

1.打包AssetBundle
先在資源的Inspector皮膚最下方 填寫資源所屬的AssetBundle名稱和字尾(字尾可以不填)
再利用BuildPipeline.BuildAssetBundles()進行打包
填寫資源包名

2.打包Scene
(1)可以利用BuildPipline.BuildAssetBundles()進行打包。
注意:場景包內只能給.unity場景檔案填寫資源包名,不能給其他資源命名,否則打包會失敗
一個場景ab包內可以包含多個場景檔案,場景需要的資源會自動關聯
有些資源是Editor下專用的。不會被打包進ab裡 比如LightingData.asset
使用方式是www載入場景ab包後 先呼叫www.assetBundle 再呼叫SceneManager.LoadScene("name")

(2)利用BuildPipeline.BuildPlayer()進行打包
為方便使用 先把要打包的場景放入指定的資料夾 通過指令碼批量打包
場景放入指定資料夾

3.指令碼批量打包
開始打包

4.打包完畢
打包完畢

5.載入測試
載入測試

6.打包和測試指令碼

AssetBundleBuilder.cs

using UnityEngine;
using UnityEditor;
using System.IO;

/// <summary>
/// 資源包打包工具
/// <para>打包AssetBundle和場景(Unity 2018.2.20)</para>
/// <para>ZhangYu 2019-02-26</para>
/// </summary>
public class AssetBundleBuilder
{
    [MenuItem("打包/Windows/資源包和場景")]
    public static void BuildAbsAndScenesWindows() {
        BuildAbsAndScenes(BuildTarget.StandaloneWindows);
    }

    [MenuItem("打包/Android/資源包和場景")]
    public static void BuildAbsAndScenesAndroid() {
        BuildAbsAndScenes(BuildTarget.Android);
    }

    [MenuItem("打包/IOS/資源包和場景")]
    public static void BuildAbsAndScenesIOS() {
        BuildAbsAndScenes(BuildTarget.iOS);
    }

    [MenuItem("打包/Windows/資源包")]
    public static void BuildAbsWindows() {
        BuildAssetBundles(BuildTarget.StandaloneWindows);
    }

    [MenuItem("打包/Android/資源包")]
    public static void BuildAbsAndroid() {
        BuildAssetBundles(BuildTarget.Android);
    }

    [MenuItem("打包/IOS/資源包")]
    public static void BuildAbsIOS() {
        BuildAssetBundles(BuildTarget.iOS);
    }

    [MenuItem("打包/Windows/場景")]
    public static void BuildScenesWindows() {
        BuildScenes(BuildTarget.StandaloneWindows);
    }

    [MenuItem("打包/Android/場景")]
    public static void BuildScenesAndroid() {
        BuildScenes(BuildTarget.Android);
    }

    [MenuItem("打包/IOS/場景")]
    public static void BuildScenesIOS() {
        BuildScenes(BuildTarget.iOS);
    }

    // 打包AssetBundle和Scenes
    public static void BuildAbsAndScenes(BuildTarget platform) {
        BuildAssetBundles(platform);
        BuildScenes(platform);
    }

    // 打包AssetBundles
    private static void BuildAssetBundles(BuildTarget platform) {
        // 輸出路徑
        string outPath = Application.streamingAssetsPath + "/Abs";
        if (!Directory.Exists(outPath)) Directory.CreateDirectory(outPath);
        EditorUtility.DisplayProgressBar("資訊", "打包資源包", 0f);
        BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.DeterministicAssetBundle, platform);
        AssetDatabase.Refresh();
        Debug.Log("所有資源包打包完畢");
    }

    // 打包Scenes
    private static void BuildScenes(BuildTarget platform) {
        // 指定場景資料夾和輸出路徑
        string scenePath = Application.dataPath + "/AbResources/Scenes";
        string outPath = Application.streamingAssetsPath + "/Abs/";

        if (Directory.Exists(scenePath)) {
            // 建立輸出資料夾
            if (!Directory.Exists(outPath)) Directory.CreateDirectory(outPath);

            // 查詢指定目錄下的場景檔案
            string[] scenes = GetAllFiles(scenePath, "*.unity");
            for (int i = 0; i < scenes.Length; i++) {
                string url = scenes[i].Replace("\\", "/");
                int index = url.LastIndexOf("/");
                string scene = url.Substring(index + 1, url.Length - index - 1);
                string msg = string.Format("打包場景{0}", scene);
                EditorUtility.DisplayProgressBar("資訊", msg, 0f);
                scene = scene.Replace(".unity", ".scene");
                Debug.Log(string.Format("打包場景{0}到{1}", url, outPath + scene));
                BuildPipeline.BuildPlayer(scenes, outPath + scene, BuildTarget.StandaloneWindows, BuildOptions.BuildAdditionalStreamedScenes);
                AssetDatabase.Refresh();
            }
            EditorUtility.ClearProgressBar();
            Debug.Log("所有場景打包完畢");
        }
    }

    /// <summary> 獲取資料夾和子資料夾下所有指定型別檔案 </summary>
    private static string[] GetAllFiles(string directory, params string[] types) {
        if (!Directory.Exists(directory)) return new string[0];
        string searchTypes = (types == null || types.Length == 0) ? "*.*" : string.Join("|", types);
        string[] names = Directory.GetFiles(directory, searchTypes, SearchOption.AllDirectories);
        return names;
    }

}

LoadTest.cs

using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadTest : MonoBehaviour {

    private void Start () {
        LoadAB();
        LoadScene();
    }

    // 載入資源包
    private void LoadAB() {
        // 資源包路徑
        string path = Application.streamingAssetsPath + "/Abs/test.ab";

        // WWW下載
        Http http = gameObject.AddComponent<Http>();
        http.get(path, OnLoadABComplete);
    }

    // 載入場景
    private void LoadScene() {
        // 資源包路徑
        string path = Application.streamingAssetsPath + "/Abs/Test.scene";

        // WWW下載
        Http http = gameObject.AddComponent<Http>();
        http.get(path, OnLoadSceneComplete);
    }

    // 載入AssetBundle完畢
    private void OnLoadABComplete(WWW www) {
        // 例項化預製
        AssetBundle ab = www.assetBundle;
        Object prefab = ab.LoadAsset("Test");
        GameObject instance = (GameObject)Instantiate(prefab);
        DontDestroyOnLoad(instance);
    }

    // 載入場景完畢
    private void OnLoadSceneComplete(WWW www) {
        // 必須寫www.assetBundle這句 這樣場景才能被讀取到
        AssetBundle ab = www.assetBundle;
        SceneManager.LoadScene("Test");
    }

}

相關文章