【轉】unity3d動態加載及生成配置文件


本文大部分轉載,作者做了關於配置文件生成工作,但是很遺憾,關於position和rotation信息目前尚未自動生成,運行本例的朋友,需要自己手動添加位置和角度信息,否則程序會報錯。
標准的json數據:
  1. {
  2.     "AssetList" : [{
  3.         "Name" : "Chair 1",
  4.         "Source" : "Prefabs/Chair001.unity3d",
  5.         "Position" : [2,0,-5],
  6.         "Rotation" : [0.0,60.0,0.0]
  7.     },
  8.     {
  9.         "Name" : "Chair 2",
  10.         "Source" : "Prefabs/Chair001.unity3d",
  11.         "Position" : [1,0,-5],
  12.         "Rotation" : [0.0,0.0,0.0]
  13.     },
  14.     {
  15.         "Name" : "Vanity",
  16.         "Source" : "Prefabs/vanity001.unity3d",
  17.         "Position" : [0,0,-4],
  18.         "Rotation" : [0.0,0.0,0.0]
  19.     }
  20.     }]
  21. }

用Unity3D制作基於web的網絡 游戲,不可避免的會用到一個技術-資源動態加載。比如想加載一個大場景的資源,不應該在游戲的開始讓用戶長時間等待全部資源的加載完畢。應該優先加載用戶附近的場景資源,在游戲的過程中,不影響操作的情況下,后台加載剩余的資源,直到所有加載完畢。

在講述代碼之前,先想象這樣一個網絡游戲的開發流程。首先美工制作場景資源的3D建模,游戲設計人員把3D建模導進Unity3D,托托拽拽編輯場景,完成后把每個gameobject導出成XXX.unity3d格式的資源文件(參看BuildPipeline),並且把整個場景的 信息生成一個配置文件,xml或者Json格式(本文使用Json)。最后還要把資源文件和場景配置文件上傳到服務器,最好使用CMS管理。客戶端運行游戲時,先讀取服務器的場景配置文件,再根據玩家的位置從服務器 下載相應的資源文件並加載,然后開始游戲,注意這里並不是下載所有的場景資源。在游戲的過程中,后台繼續加載資源直到所有加載完畢。
json.txt:( 注:當生成的json無法讀取時,記得改一下編碼格式 改成 ANSI
{"AssetList":[{"Name":"Sphere","Source":"Prefabs/Sphere.unity3d"},{"Name":"cube","Source":"Prefabs/cube.unity3d"},{"Name":"Sphere","Source":"Prefabs/Sphere.unity3d"},{"Name":"cube","Source":"Prefabs/cube.unity3d"}]}

主程序:
1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class MainMonoBehavior : MonoBehaviour {
 5 
 6     public delegate void MainEventHandler(GameObject dispatcher);
 7     public event MainEventHandler StartEvent;
 8     public event MainEventHandler UpdateEvent;
 9     public void Start()
10     {
11         ResourceManager.getInstance().LoadSence("Scenes/json.txt");//json配置文件
12         if(StartEvent != null)
13         {
14             StartEvent(this.gameObject);
15         }
16     }
17     public void Update()
18     {
19         if (UpdateEvent != null)
20         {
21             UpdateEvent(this.gameObject);
22         }
23     }
24 }

 

這里面用到了C#的事件機制,大家可以看看我以前 翻譯過的 國外一個牛人的文章。 C# 事件和Unity3D
在 start方法里調用ResourceManager,先加載配置文件。每一次調用update方法,MainMonoBehavior會把update 事件分發給ResourceManager,因為ResourceManager注冊了MainMonoBehavior的update事件。

輔助類:
ResourceManager.cs
  1 using UnityEngine;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using LitJson;
  5 using System.Net;
  6 public class ResourceManager
  7 {
  8 
  9 // Use this for initialization
 10         private MainMonoBehavior mainMonoBehavior;
 11         private   string mResourcePath;
 12         private Scene mScene;
 13         private Asset mSceneAsset;
 14         private static ResourceManager resourceManager=new ResourceManager();//如果沒有new 會出現沒有實例化的錯誤
 15         private Dictionary<string ,WWW > wwwCacheMap=new Dictionary<string,WWW>();//這個新添加的原文代碼中沒有定義它 應該是個字典
 16        public static  ResourceManager getInstance( )
 17         {
 18                 return resourceManager;//靜態函數中不能使用非靜態成員
 19         }
 20         public  ResourceManager()
 21         {
 22                 mainMonoBehavior = GameObject.Find("Main Camera").GetComponent<MainMonoBehavior>();
 23                 mResourcePath ="file://"+Application.dataPath+"/..";
 24         }
 25        
 26         public void LoadSence(string fileName)
 27         {
 28                 //Debug.Log(fileName);
 29                 mSceneAsset = new Asset();
 30                 mSceneAsset.Type = Asset.TYPE_JSON;//后面類型判斷有用
 31                 mSceneAsset.Source = fileName;
 32                 mainMonoBehavior.UpdateEvent += OnUpdate;//添加監聽函數
 33         }
 34 
 35 
 36 
 37         public void OnUpdate(GameObject dispatcher)//該函數是監聽函數,每幀都會被調用(它的添加是在MainMonoBehavior的start函數中通過調用本地LoadSence函數)
 38         {
 39                 if (mSceneAsset != null)//表示已經通過了new操作分配類內存空間但是資源還沒有加載完
 40                 {
 41                         LoadAsset(mSceneAsset);//這個函數里面會通過判斷,使www的new操作只執行一次
 42                         if (!mSceneAsset.isLoadFinished)//C#中 bool類型默認是false
 43                         {
 44                                return;
 45                         }
 46                         mScene = null;
 47                         mSceneAsset = null;
 48                 }
 49                 mainMonoBehavior.UpdateEvent -= OnUpdate;//當所有資源被加載后,刪除監聽函數。
 50         }
 51         //最核心的函數
 52      private Asset LoadAsset(Asset asset)
 53         {
 54                 string fullFileName =mResourcePath+"/"+ asset.Source;// mResourcePath + "/" + asset.Source;
 55                 Debug.Log("fullFileName=" + fullFileName);
 56                 //if www resource is new, set into www cache
 57                 if (!wwwCacheMap.ContainsKey(fullFileName))
 58                 {//自定義字典 查看開頭的定義
 59                         if (asset.www == null)
 60                         {//表示www還沒有new操作
 61                                 asset.www = new WWW(fullFileName);
 62                                 return null;
 63                         }
 64                         if (!asset.www.isDone)
 65                         {
 66                                 return null;
 67                         }
 68                         wwwCacheMap.Add(fullFileName, asset.www); //該字典是作為緩存的作用,如果之前已經加載過同樣的Unity3D格式文件,那么不需要在加載,直接拿來用就行了。  
 69                 }  
 70                 if (asset.Type == Asset.TYPE_JSON)
 71                 { //Json 表示當txt文件被首次加載時的處理
 72                         if (mScene == null)
 73                         {        
 74                             string jsonTxt = mSceneAsset.www.text;
 75                             Debug.Log("jsonTxt=" + jsonTxt);
 76                             mScene = JsonMapper.ToObject<Scene>(jsonTxt);//mScene是個Asset對象列表,也就是Json文件需要一個AssetList列表對象,注意名字的統一,列表中Asset對象中的成員名稱要和txt                //文件中的相關名稱統一 不然JsonMapper無法找到
 77                          }
 78                         //load scene
 79                         foreach (Asset sceneAsset in mScene.AssetList)
 80                         {
 81                                 if (sceneAsset.isLoadFinished)
 82                                 {
 83                                         continue;
 84                                 }
 85                                 else
 86                                 {
 87                                         LoadAsset(sceneAsset);//這里的處理就是 下面 Asset.TYPE_GAMEOBJECT的處理方式,注意是遞歸函數的調用
 88                                         if (!sceneAsset.isLoadFinished)
 89                                         {
 90                                             return null;
 91                                          }
 92                                  }
 93                         }
 94                 }
 95                 else if (asset.Type == Asset.TYPE_GAMEOBJECT)//處理文件中具體信息,嵌套關系或者直接是一個GameObject對象,與上面的代碼有聯系,Asset創建時候的構造函數中設置成
 96                 //TYPE_GAMEOBJECT類型
 97                 { //Gameobject
 98                         if (asset.gameObject == null)//如果不為null 表示已經通過wwwCacheMap加載了資源包中所包含的資源(fullFileName僅僅是一個文件,資源包中資源是分散的GameObject對象),不需要在重新加載
 99                         {
100                                 wwwCacheMap[fullFileName].assetBundle.LoadAll();//已經通過new WWW操作完成了加載,該函數用來加載包含着資源包中的資源
101                                 GameObject go = (GameObject)GameObject.Instantiate(wwwCacheMap[fullFileName].assetBundle.mainAsset);
102                                 UpdateGameObject(go, asset);
103                                 asset.gameObject = go;
104                         }
105                         if (asset.AssetList != null)//有嵌套關系
106                         {
107                                 foreach (Asset assetChild in asset.AssetList)
108                                 {
109                                         if (assetChild.isLoadFinished)
110                                         {
111                                                 continue;
112                                         }
113                                         else
114                                         {
115                                                 Asset assetRet = LoadAsset(assetChild);
116                                                 if (assetRet != null)//這個if else 語句是為了防止你的配置文件中的GameObject對象路徑不正確,導致訪問空指針。
117                                                 {
118                                                         assetRet.gameObject.transform.parent = asset.gameObject.transform;
119                                                 }
120                                                 else
121                                                 {
122                                                         return null;
123                                                 }
124                                         }
125                                 }
126                         }
127                 }
128                 asset.isLoadFinished = true;
129                 return asset;
130         }
131         private void UpdateGameObject(GameObject go, Asset asset)
132         {
133                 //name
134                 go.name = asset.Name;
135                 //position
136                 Vector3 vector3 = new Vector3((float)asset.Position[0], (float)asset.Position[1], (float)asset.Position[2]);
137                 go.transform.position = vector3;
138                 //rotation
139                vector3 = new Vector3((float)asset.Rotation[0], (float)asset.Rotation[1], (float)asset.Rotation[2]);
140                 go.transform.eulerAngles = vector3;
141         }
142 }
View Code
 1 Asset.cs類:
 2 using UnityEngine;
 3 using System.Collections.Generic;
 4 public class Asset
 5 {
 6         public const byte TYPE_JSON = 1;
 7         public const byte TYPE_GAMEOBJECT = 2;
 8         public Asset()
 9         {
10             //default type is gameobject for json load
11             Type = TYPE_GAMEOBJECT;
12         }
13         public byte Type
14         {
15             get;
16             set;
17         }
18         public string Name
19         {
20             get;
21             set;
22         }
23         public string Source
24         {
25             get;
26             set;
27         }
28         public double[] Bounds
29         {
30             get;
31             set;
32         }
33        
34         public double[] Position
35         {
36             get;
37             set;
38         }
39         public double[] Rotation
40         {
41             get;
42             set;
43         }
44         public List<Asset> AssetList
45         {
46             get;
47             set;
48         }
49         public bool isLoadFinished
50         {
51             get;
52             set;
53         }
54         public WWW www
55         {
56             get;
57             set;
58         }
59         public GameObject gameObject
60         {
61             get;
62             set;
63         }
64 }
65 Scene.cs類:
66 using System.Collections.Generic;
67 
68 public class Scene
69 {
70         public List<Asset> AssetList
71         {
72             get;
73             set;
74         }
75 }


生成.unity3d代碼:

View Code
 1 using UnityEngine;
 2 using UnityEditor;
 3 using System.IO;
 4 using System;
 5 using System.Text;
 6 using System.Collections.Generic;
 7 using LitJson;
 8 public class BuildAssetBundlesFromDirectory
 9 {
10       static List<JsonResource> config=new List<JsonResource>();
11       static Dictionary<string, List<JsonResource>> assetList=new Dictionary<string, List<JsonResource>>();
12         [@MenuItem("Asset/Build AssetBundles From Directory of Files")]//這里不知道為什么用"@",添加菜單
13         static void ExportAssetBundles ()
14         {//該函數表示通過上面的點擊響應的函數
15                    assetList.Clear();
16                    string path = AssetDatabase.GetAssetPath(Selection.activeObject);//Selection表示你鼠標選擇激活的對象
17                   Debug.Log("Selected Folder: " + path);
18        
19        
20                   if (path.Length != 0)
21                   {
22                            path = path.Replace("Assets/", "");//因為AssetDatabase.GetAssetPath得到的是型如Assets/文件夾名稱,且看下面一句,所以才有這一句。
23                             Debug.Log("Selected Folder: " + path);
24                            string [] fileEntries = Directory.GetFiles(Application.dataPath+"/"+path);//因為Application.dataPath得到的是型如 "工程名稱/Assets"
25                            
26                            string[] div_line = new string[] { "Assets/" };
27                            foreach(string fileName in fileEntries)
28                            {
29                                     j++;
30                                     Debug.Log("fileName="+fileName);
31                                     string[] sTemp = fileName.Split(div_line, StringSplitOptions.RemoveEmptyEntries);
32                                     string filePath = sTemp[1];
33                                      Debug.Log(filePath);
34                                     filePath = "Assets/" + filePath;
35                                     Debug.Log(filePath);
36                                     string localPath = filePath;
37                                     UnityEngine.Object t = AssetDatabase.LoadMainAssetAtPath(localPath);
38                                    
39                                      //Debug.Log(t.name);
40                                     if (t != null)
41                                     {
42                                             Debug.Log(t.name);
43                                             JsonResource jr=new JsonResource();
44                                             jr.Name=t.name;
45                                             jr.Source=path+"/"+t.name+".unity3d";
46                                               Debug.Log( t.name);
47                                             config.Add(jr);//實例化json對象
48                                               string bundlePath = Application.dataPath+"/../"+path;
49                                                if(!File.Exists(bundlePath))
50                                                 {
51                                                    Directory.CreateDirectory(bundlePath);//在Asset同級目錄下相應文件夾
52                                                 }
53                                               bundlePath+="/"  + t.name + ".unity3d";
54                                              Debug.Log("Building bundle at: " + bundlePath);
55                                              BuildPipeline.BuildAssetBundle(t, null, bundlePath, BuildAssetBundleOptions.CompleteAssets);//在對應的文件夾下生成.unity3d文件
56                                     } 
57                            }
58                             assetList.Add("AssetList",config);
59                             for(int i=0;i<config.Count;i++)
60                             {
61                                     Debug.Log(config[i].Source);
62                             }
63                   }
64                 string data=JsonMapper.ToJson(assetList);//序列化數據
65                 Debug.Log(data);
66         string jsonInfoFold=Application.dataPath+"/../Scenes";
67         if(!Directory.Exists(jsonInfoFold))
68         {
69             Directory.CreateDirectory(jsonInfoFold);//創建Scenes文件夾
70         }
71                 string fileName1=jsonInfoFold+"/json.txt";
72                 if(File.Exists(fileName1))
73                 {
74                     Debug.Log(fileName1 +"already exists");
75                     return;
76                 }
77                 UnicodeEncoding uni=new UnicodeEncoding();
78                   
79                 using(  FileStream  fs=File.Create(fileName1))//向創建的文件寫入數據
80                 {
81                         fs.Write(uni.GetBytes(data),0,uni.GetByteCount(data));
82                         fs.Close();
83                 }
84       }
85 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM