unity3d 動態加載資源Resources.Load和AssetBundle

1.首先總結下unity有哪幾種資源類型

     unity資源的類型:

    -a) Unity內置的常用asset,                   fbx\jpg...

  - b) textasset:                                         txt、binary等,對應了它的TextAsset類,可以直接讀入文本或者二進制byte

   -c) scriptable object                             它是序列化的Object實例,例如把一個Object實例保存成scriptable object,讀入進來後就直接在內存中變 成那個實例

    - d) asset bundle                                  它是一個資源壓縮包,裏面包含了一堆資源

 

通常我們自定義的文件類型可以通過textasset 或scriptable object 來存儲,區別在於前者是一個字節或文本流,後者要對應於程序中一個定義了的類型,textasset 還通常用於資源的加密。

 

2.動態load資源的幾種途徑:

   -通過Resources模塊,調用它的load函數:可以直接load並返回某個類型的Object,前提是要把這個資源放在Resource命名的文件夾下,Unity不關有沒有場景引用,都會將其全部打入到安裝包中。

        -通過bundle的形式:即將資源打成 asset bundle 放在服務器或本地磁盤,然後使用WWW模塊get 下來,然後從這個bundle中load某個object。

        -通過AssetDatabase.loadasset :這種方式只在editor範圍內有效,遊戲運行時沒有這個函數,它通常是在開發中調試用的

 

       Resources的方式需要把所有資源全部打入安裝包,這對遊戲的分包發佈(微端)和版本升級(patch)是不利的,所以unity推薦的方式是不用它,都用bundle的方式替代,把資源達成幾個小的bundle,用哪個就load哪個,這樣還能分包發佈和patch,但是在開發過程中,不可能沒更新一個資源就打一次bundle,所以editor環境下可以使用AssetDatabase來模擬,這通常需要我們封裝一個dynamic resource的loader模塊,在不同的環境下做不同實現。

 

3.動態資源的存放

  有時我需要存放一些自己的文件在磁盤上,例如我想把幾個bundle放在初始的安裝裏, unity有一個streaming asset的概念,用於提供存儲接口的訪問。我們需要在編輯器建立一個StreamingAssets名字的文件夾,把需要我們放在客戶磁盤上的動態文件放在這個文件夾下面,這樣安裝後,這些文件會放在用戶磁盤的指定位置,這個位置可以通過Application.streamingAssetsPath來得到。

 

  初步整理並且學習unity3d資源加載方法,預計用時兩天完成入門學習Unity3d常用兩種加載資源方案:Resources.Load和AssetBundle

Resources.Load就是從一個缺省打進程序包裏的AssetBundle里加載資源而一般AssetBundle文件需要你自己創建,運行時動態加載,

可以指定路徑和來源的。其實場景裏所有靜態的對象也有這麼一個加載過程,只是Unity後臺替你自動完成

一:Resources.Load:使用這種方式加載資源,首先需要下Asset目錄下創建一個名爲Resources的文件夾,這個命名是U3D規定的方式,然後把資源文件放進去,

當然也可以在Resources中再創建子文件夾,當然在代碼加載時需要添加相應的資源路徑,下面是一個簡demo,兩個預設,Cube和Sphere,

其中Cube放在Resource中的Prebs中,而Sphere放在Resources跟目錄下,下面分別實現Resources.Load資源的加載

 

複製代碼

using UnityEngine;
using System.Collections;

public class LoadResDemo : MonoBehaviour {

    private string cubePath = "Prebs/MyCubePreb";
    private string spherePath = "MySpherePreb";
    void Start () {
        //把資源加載到內存中
        Object  cubePreb = Resources.Load(cubePath, typeof(GameObject));
        //用加載得到的資源對象,實例化遊戲對象,實現遊戲物體的動態加載
        GameObject cube = Instantiate(cubePreb) as GameObject;



        //以下同理實現Sphere的動態實例化
        //把資源加載到內存中
        Object spherePreb = Resources.Load(spherePath, typeof(GameObject));
        //用加載得到的資源對象,實例化遊戲對象,實現遊戲物體的動態加載
        GameObject sphere = Instantiate(spherePreb) as GameObject;
    }
    
    void Update () {
    
    }
}

複製代碼

  將上面的腳本附加到某個遊戲對象上,在運行遊戲時就可以看到場景中動態創建的上面的遊戲對象了

上面是第一種使用Resources.Load()的方式動態加載遊戲對象的,然而在項目中更長用的卻是第二種使用AssetBundle的方式動態加載遊戲對象。

 

二、使用AssetBundle打包預設或者場景可以將與其相關的所有資源打包,這樣很好地解決資源的依賴問題,使得我們可以方便的加載GameObject

首先需要打包資源:

複製代碼

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
public class AesstBundleTest : MonoBehaviour {



    [MenuItem("Custom Bundle/Create Bundel Main")]
    public static void creatBundleMain()
    {
        //獲取選擇的對象的路徑
        Object[] os = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        bool isExist = Directory.Exists(Application.dataPath + "/StreamingAssets");
        if (!isExist)
        {
            Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
        }
        foreach (Object o in os)
        {
            string sourcePath = AssetDatabase.GetAssetPath(o);

            string targetPath = Application.dataPath + "/StreamingAssets/" + o.name + ".assetbundle";
            if (BuildPipeline.BuildAssetBundle(o, null, targetPath, BuildAssetBundleOptions.CollectDependencies))
            {
                print("create bundle cuccess!");
            }
            else
            {
                print("failure happen");
            }
            AssetDatabase.Refresh();
        }
    }
    [MenuItem("Custom Bundle/Create Bundle All")]
    public static void CreateBundleAll()
    {
        bool isExist = Directory.Exists(Application.dataPath + "/StreamingAssets");
        if (!isExist)
        {
            Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
        }
        Object[] os = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        if (os == null || os.Length == 0)
        {
            return;
        }
        string targetPath = Application.dataPath + "/StreamingAssets/" + "All.assetbundle";
        if (BuildPipeline.BuildAssetBundle(null, os, targetPath, BuildAssetBundleOptions.CollectDependencies))
        {
            print("create bundle all cuccess");
        }
        else
        {
            print("failure happen");
        }
        AssetDatabase.Refresh();
    }

}

複製代碼

把上面的代碼放在Editor中,在菜單欄中就可以看見自定的菜單項,選中需要打包的預設,就可以把對應的預設打包並輸出到StreamAssets中了

然後是動態加載資源:

複製代碼

using UnityEngine;
using System.Collections;

public class LoadBundleTest : MonoBehaviour {
    //不同平臺下StreamingAssets的路徑是不同的,這裏需要注意一下。
    public static readonly string PathURL =
    #if UNITY_ANDROID
        "jar:file://" + Application.dataPath + "!/assets/";
    #elif UNITY_IPHONE
        Application.dataPath + "/Raw/";
    #elif UNITY_STANDALONE_WIN || UNITY_EDITOR
    "file://" + Application.dataPath + "/StreamingAssets/";
    #else
        string.Empty;
    #endif



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

    void OnGUI()
    {
        if (GUILayout.Button("Load Bundle Main"))
        {
            string path_shpere = PathURL + "MySpherePreb.assetbundle";
            StartCoroutine(loadBundleMain(path_shpere));

            string path_cube = PathURL + "MyCubePreb.assetbundle";
            StartCoroutine(loadBundleMain(path_cube));
            print(path_cube);
        }

        if (GUILayout.Button("Load Bundle All"))
        {
            StartCoroutine(loadBundleAll(PathURL + "All.assetbundle"));
        }
    }


    private IEnumerator loadBundleMain(string path)
    {
        WWW bundle = new WWW(path);
      //  yield return bundle;
         Instantiate(bundle.assetBundle.mainAsset);
         bundle.assetBundle.Unload(false);
         yield return 1;
    }

    private IEnumerator loadBundleAll(string path)
    {
        WWW bundle = new WWW(path);
        yield return bundle;
        Instantiate(bundle.assetBundle.Load("MyCubePreb"));
        Instantiate(bundle.assetBundle.Load("MySpherePreb"));
        yield return 1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章