2012-07-03

Unity 3D 列出 AssetBundle 內容

AssetBundle.LoadAll 指令取得的資料型態是 Object[] ,利用 C# Reflection 功能可以把它轉回原型並取得其中某個成員 (Property value) 的值。程式碼列出如下:
[MenuItem("Assets/Get Content List of Assetbundle")]
static void ListABContent()
{
    string strPath = EditorUtility.OpenFilePanel(
            "Open AssetBundle...", 
            Application.dataPath, 
            "unity3d");
    if (System.IO.File.Exists(strPath) == true)
    {
        WWW fileLoader = new WWW("file://" + strPath);
        object[] content = fileLoader.assetBundle.LoadAll();
 
        Debug.Log("total objects =" + content.Length);
 
        for (int i = 0; i < content.Length; ++i)
        {
            System.Type objType = content[i].GetType();
            System.Reflection.PropertyInfo objProperty = 
                objType.GetProperty("name");
 
            string objName = "<error>";
            try
            {
                objName = (string)objProperty.GetValue(content[i], null);
            }
            catch
            {
            }
 
            Debug.Log(
                "obj[" + i + "] : type="+objType.Name+", name=" + objName
                );
 
        }
 
        fileLoader.assetBundle.Unload(true);
        fileLoader.Dispose();
    }
    else
        Debug.LogError("file not found");
 
}

把程式碼儲存在 C# Script,並置於 Editor 目錄之下,沒問題的話,功能表的 Assets 之下會多出一項 "Get Content List of Assetbundle",點擊之後選擇 Assetbundle 檔案,console 視窗將列出此 assetbundle 之下所有物件的型態 (Type) 及其名稱 (name)。

底下另外註記呼叫成員函數 (invoke method) 的方法:( 假設取得的 object 為 Texture2D,則呼叫其 GetPixels Method 的方法)

System.Reflection.MethodInfo GetPixels_Default = 
    objType.GetMethod("GetPixels", new System.Type[0]);
System.Reflection.MethodInfo GetPixels_Mipmap =
    objType.GetMethod("GetPixels", new System.Type[1] {typeof(int)});
Color[] retPixels;
retPixels =(Color[])GetPixels_Default.Invoke(content[i], null);
retPixels = (Color[])GetPixels_Mipmap.Invoke(content[i], new object[1] { 0 });

0 意見 :

張貼留言