1. 程式人生 > >在unity2017中載入AssetBundle檔案

在unity2017中載入AssetBundle檔案

一、使用AssetBundle打包檔案

二、在本地載入AssetBundle檔案

呼叫loadAsset方法即可
具體指令碼如下:

    string path = "Assets/StreamingAssets/all.unity3d";
    void OnGUI()
    {
        if (GUILayout.Button("Single Obj"))
        {
            LoadSingleObject();
        }
        if(GUILayout.Button("All Objs"))
        {
            LoadAllObjects();
        }
    }
    
    /// <summary>
    /// 載入單個檔案
    /// </summary>
    private void LoadSingleObject()
    {
        AssetBundle ab = AssetBundle.LoadFromFile(path);
        GameObject prefab = ab.LoadAsset<GameObject>("WhiteChess");      //檔名需要和打包時的檔名一致
        Instantiate(prefab);
    }

    /// <summary>
    /// 載入所有檔案
    /// </summary>
    private void LoadAllObjects()
    {
        AssetBundle ab = AssetBundle.LoadFromFile(path);
        Object[] objs = ab.LoadAllAssets();                            
        foreach (var obj in objs)
        {
            Instantiate(obj);
        }
//         ab.Unload(true);                        //同時載入某個assetbundle檔案中的資源,會出現報錯,需要unload
    }