1. 程式人生 > >[unity3d]unity中打包成.unity3d格式並實現本地加載出來

[unity3d]unity中打包成.unity3d格式並實現本地加載出來

1.首先我們把這段程式碼拷貝下來,放進工程,不要託給任何物體,就放在那不要理它。

using UnityEngine;
using UnityEditor;
public class ExportAssetBundles {
    [MenuItem("Export/Build AssetBundle From Selection - Track dependencies")]
    static void ExportResource () {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {
            // Build the resource file from the active selection.
        Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
            Selection.objects = selection;
        }
    }
    [MenuItem("Export/Build AssetBundle From Selection - No dependency tracking")]
    static void ExportResourceNoTrack () {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {
            // Build the resource file from the active selection.
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
        }
    }
}
我們仔細看一下,其實打包的.unity3d格式的檔案也類似assenbundle,只不過是換了個不同的字尾名而已。

當我們建立完,儲存好後我,我們會發現選單的導航欄多了這2項

2.我們在選中我們需要打包的預設物體(也即是Prefab)。然後選中上面的第一項進行打包成.unity3d格式的檔案。如圖

3.設定名字,路徑等(路徑很重要,待會載入會用到。)如圖:

4.重新整理下。你就會看見這個了:

這個就是我們打包後動態載入的內容。

5. 現在我來說下怎麼動態載入它吧,直接上程式碼

using UnityEngine;
using System.Collections;
using System.IO;

public class LoadUnity3d : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

        StartCoroutine(LoadScene());

    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator LoadScene()
    {
        //檔案路徑,也就是我們打包的那個
        WWW www = new WWW("file:///" + Application.dataPath + "/Bundles/My Prefab.unity3d");
        yield return www;
        Instantiate(www.assetBundle.mainAsset);
    }
}

6.我們再新建一個空物體,講我們這個指令碼託給他,執行,你就能看見我們的預設也加載出來了。

  效果如下: