在Unity3D的網絡遊戲中實現資源動態加載

用Unity3D製做基於web的網絡遊戲,不可避免的會用到一個技術-資源動態加載。好比想加載一個大場景的資源,不該該在遊戲的開始讓用戶長時間等待所有資源的加載完畢。應該優先加載用戶附近的場景資源,在遊戲的過程當中,不影響操做的狀況下,後臺加載剩餘的資源,直到全部加載完畢。 

本文包含一些代碼片斷講述實現這個技術的一種方法。本方法不必定是最好的,但願能拋磚引玉。代碼是C#寫的,用到了Json,還有C#的事件機制。 

在講述代碼以前,先想象這樣一個網絡遊戲的開發流程。首先美工製做場景資源的3D建模,遊戲設計人員把3D建模導進Unity3D,託託拽拽編輯場景,完成後把每一個gameobject導出成XXX.unity3d格式的資源文件(參看BuildPipeline),而且把整個場景的信息生成一個配置文件,xml或者Json格式(本文使用Json)。最後還要把資源文件和場景配置文件上傳到服務器,最好使用CMS管理。客戶端運行遊戲時,先讀取服務器的場景配置文件,再根據玩家的位置從服務器下載相應的資源文件並加載,而後開始遊戲,注意這裏並非下載全部的場景資源。在遊戲的過程當中,後臺繼續加載資源直到全部加載完畢。 

一個簡單的場景配置文件的例子: 
MyDemoSence.txt web

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.         "Name" : "Writing Table",  
  22.         "Source" : "Prefabs/writingTable001.unity3d",  
  23.         "Position" : [0,0,-7],  
  24.         "Rotation" : [0.0,0.0,0.0],  
  25.         "AssetList" : [{  
  26.             "Name" : "Lamp",  
  27.             "Source" : "Prefabs/lamp001.unity3d",  
  28.             "Position" : [-0.5,0.7,-7],  
  29.             "Rotation" : [0.0,0.0,0.0]  
  30.         }]  
  31.     }]  
  32. }  


AssetList:場景中資源的列表,每個資源都對應一個unity3D的gameobject 
Name:gameobject的名字,一個場景中不該該重名 
Source:資源的物理路徑及文件名 
Position:gameobject的座標 
Rotation:gameobject的旋轉角度 
你會注意到Writing Table裏面包含了Lamp,這兩個對象是父子的關係。配置文件應該是由程序生成的,手工也能夠修改。另外在遊戲上線後,客戶端接收到的配置文件應該是加密並壓縮過的。 

主程序: json

C#代碼   收藏代碼
  1. 。。。  
  2. public class MainMonoBehavior : MonoBehaviour {  
  3.   
  4.     public delegate void MainEventHandler(GameObject dispatcher);  
  5.   
  6.     public event MainEventHandler StartEvent;  
  7.     public event MainEventHandler UpdateEvent;  
  8.   
  9.     public void Start() {  
  10.         ResourceManager.getInstance().LoadSence("Scenes/MyDemoSence.txt");  
  11.   
  12.         if(StartEvent != null){  
  13.             StartEvent(this.gameObject);  
  14.         }  
  15.     }  
  16.   
  17.     public void Update() {  
  18.         if (UpdateEvent != null) {  
  19.             UpdateEvent(this.gameObject);  
  20.         }  
  21.     }  
  22. }  
  23. 。。。  
  24. }  


這裏面用到了C#的事件機制,你們能夠看看我之前翻譯過的國外一個牛人的文章。C# 事件和Unity3D 
在start方法裏調用ResourceManager,先加載配置文件。每一次調用update方法,MainMonoBehavior會把update事件分發給ResourceManager,由於ResourceManager註冊了MainMonoBehavior的update事件。 

ResourceManager.cs 緩存

C#代碼   收藏代碼
  1. 。。。  
  2. private MainMonoBehavior mainMonoBehavior;  
  3. private string mResourcePath;  
  4. private Scene mScene;  
  5. private Asset mSceneAsset;  
  6.   
  7. private ResourceManager() {  
  8.     mainMonoBehavior = GameObject.Find("Main Camera").GetComponent<MainMonoBehavior>();  
  9.     mResourcePath = PathUtil.getResourcePath();  
  10. }  
  11.   
  12. public void LoadSence(string fileName) {  
  13.     mSceneAsset = new Asset();  
  14.     mSceneAsset.Type = Asset.TYPE_JSON;  
  15.     mSceneAsset.Source = fileName;  
  16.   
  17.     mainMonoBehavior.UpdateEvent += OnUpdate;  
  18. }  
  19. 。。。  


在LoadSence方法裏先建立一個Asset的對象,這個對象是對應於配置文件的,設置type是Json,source是傳進來的「Scenes/MyDemoSence.txt」。而後註冊MainMonoBehavior的update事件。 服務器

C#代碼   收藏代碼
  1. public void OnUpdate(GameObject dispatcher) {  
  2.     if (mSceneAsset != null) {  
  3.         LoadAsset(mSceneAsset);  
  4.         if (!mSceneAsset.isLoadFinished) {  
  5.             return;  
  6.         }  
  7.   
  8.         //clear mScene and mSceneAsset for next LoadSence call  
  9.         mScene = null;  
  10.         mSceneAsset = null;  
  11.     }  
  12.   
  13.     mainMonoBehavior.UpdateEvent -= OnUpdate;  
  14. }  


OnUpdate方法裏調用LoadAsset加載配置文件對象及全部資源對象。每一幀都要判斷是否加載結束,若是結束清空mScene和mSceneAsset對象爲下一次加載作準備,而且取消update事件的註冊。 

最核心的LoadAsset方法: 網絡

C#代碼   收藏代碼
  1. private Asset LoadAsset(Asset asset) {  
  2.   
  3.     string fullFileName = mResourcePath + "/" + asset.Source;  
  4.       
  5.     //if www resource is new, set into www cache  
  6.     if (!wwwCacheMap.ContainsKey(fullFileName)) {  
  7.         if (asset.www == null) {  
  8.             asset.www = new WWW(fullFileName);  
  9.             return null;  
  10.         }  
  11.   
  12.         if (!asset.www.isDone) {  
  13.             return null;  
  14.         }  
  15.         wwwCacheMap.Add(fullFileName, asset.www);  
  16.     }  
  17. 。。。  


傳進來的是要加載的資源對象,先獲得它的物理地址,mResourcePath是個全局變量保存資源服務器的網址,獲得fullFileName相似http://www.mydemogame.com/asset/Prefabs/xxx.unity3d。而後經過wwwCacheMap判斷資源是否已經加載完畢,若是加載完畢把加載好的www對象放到Map裏緩存起來。看看前面Json配置文件,Chair 1和Chair 2用到了同一個資源Chair001.unity3d,加載Chair 2的時候就不須要下載了。若是當前幀沒有加載完畢,返回null等到下一幀再作判斷。這就是WWW類的特色,剛開始用WWW下載資源的時候是不能立刻使用的,要等待諾幹幀下載完成之後纔可使用。能夠用yield返回www,這樣代碼簡單,可是C#要求調用yield的方法返回IEnumerator類型,這樣限制太多不靈活。 

繼續LoadAsset方法: app

C#代碼   收藏代碼
  1. 。。。  
  2.     if (asset.Type == Asset.TYPE_JSON) { //Json  
  3.         if (mScene == null) {  
  4.             string jsonTxt = mSceneAsset.www.text;  
  5.             mScene = JsonMapper.ToObject<Scene>(jsonTxt);  
  6.         }  
  7.           
  8.         //load scene  
  9.         foreach (Asset sceneAsset in mScene.AssetList) {  
  10.             if (sceneAsset.isLoadFinished) {  
  11.                 continue;  
  12.             } else {  
  13.                 LoadAsset(sceneAsset);  
  14.                 if (!sceneAsset.isLoadFinished) {  
  15.                     return null;  
  16.                 }  
  17.             }  
  18.         }  
  19.     }   
  20. 。。。  


代碼可以運行到這裏,說明資源都已經下載完畢了。如今開始加載處理資源了。第一次確定是先加載配置文件,由於是Json格式,用JsonMapper類把它轉換成C#對象,我用的是LitJson開源類庫。而後循環遞歸處理場景中的每個資源。若是沒有完成,返回null,等待下一幀處理。 

繼續LoadAsset方法: 測試

C#代碼   收藏代碼
  1. 。。。  
  2.     else if (asset.Type == Asset.TYPE_GAMEOBJECT) { //Gameobject  
  3.         if (asset.gameObject == null) {  
  4.             wwwCacheMap[fullFileName].assetBundle.LoadAll();  
  5.             GameObject go = (GameObject)GameObject.Instantiate(wwwCacheMap[fullFileName].assetBundle.mainAsset);  
  6.             UpdateGameObject(go, asset);  
  7.             asset.gameObject = go;  
  8.         }  
  9.   
  10.         if (asset.AssetList != null) {  
  11.             foreach (Asset assetChild in asset.AssetList) {  
  12.                 if (assetChild.isLoadFinished) {  
  13.                     continue;  
  14.                 } else {  
  15.                     Asset assetRet = LoadAsset(assetChild);  
  16.                     if (assetRet != null) {  
  17.                         assetRet.gameObject.transform.parent = asset.gameObject.transform;  
  18.                     } else {  
  19.                         return null;  
  20.                     }  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  
  25.   
  26.     asset.isLoadFinished = true;  
  27.     return asset;  
  28. }  


終於開始處理真正的資源了,從緩存中找到www對象,調用Instantiate方法實例化成Unity3D的gameobject。UpdateGameObject方法設置gameobject各個屬性,如位置和旋轉角度。而後又是一個循環遞歸爲了加載子對象,處理gameobject的父子關係。注意若是LoadAsset返回null,說明www沒有下載完畢,等到下一幀處理。最後設置加載完成標誌返回asset對象。 

UpdateGameObject方法: 字體

C#代碼   收藏代碼
  1. private void UpdateGameObject(GameObject go, Asset asset) {  
  2.     //name  
  3.     go.name = asset.Name;  
  4.   
  5.     //position  
  6.     Vector3 vector3 = new Vector3((float)asset.Position[0], (float)asset.Position[1], (float)asset.Position[2]);  
  7.     go.transform.position = vector3;  
  8.   
  9.     //rotation  
  10.     vector3 = new Vector3((float)asset.Rotation[0], (float)asset.Rotation[1], (float)asset.Rotation[2]);  
  11.     go.transform.eulerAngles = vector3;  
  12. }  


這裏只設置了gameobject的3個屬性,眼力好的同窗必定會發現這些對象都是「死的」,由於少了腳本屬性,它們不會和玩家交互。設置腳本屬性要複雜的多,編譯好的腳本隨着主程序下載到本地,它們也應該經過配置文件加載,再經過C#的反射建立腳本對象,賦給相應的gameobject。 

最後是Scene和asset代碼: 動畫

C#代碼   收藏代碼
  1. public class Scene {  
  2.     public List<Asset> AssetList {  
  3.         get;  
  4.         set;  
  5.     }  
  6. }  
  7.   
  8. public class Asset {  
  9.   
  10.     public const byte TYPE_JSON = 1;  
  11.     public const byte TYPE_GAMEOBJECT = 2;  
  12.   
  13.     public Asset() {  
  14.         //default type is gameobject for json load  
  15.         Type = TYPE_GAMEOBJECT;  
  16.     }  
  17.   
  18.     public byte Type {  
  19.         get;  
  20.         set;  
  21.     }  
  22.   
  23.     public string Name {  
  24.         get;  
  25.         set;  
  26.     }  
  27.   
  28.     public string Source {  
  29.         get;  
  30.         set;  
  31.     }  
  32.   
  33.     public double[] Bounds {  
  34.         get;  
  35.         set;  
  36.     }  
  37.       
  38.     public double[] Position {  
  39.         get;  
  40.         set;  
  41.     }  
  42.   
  43.     public double[] Rotation {  
  44.         get;  
  45.         set;  
  46.     }  
  47.   
  48.     public List<Asset> AssetList {  
  49.         get;  
  50.         set;  
  51.     }  
  52.   
  53.     public bool isLoadFinished {  
  54.         get;  
  55.         set;  
  56.     }  
  57.   
  58.     public WWW www {  
  59.         get;  
  60.         set;  
  61.     }  
  62.   
  63.     public GameObject gameObject {  
  64.         get;  
  65.         set;  
  66.     }  
  67. }  



代碼就講完了,在我實際測試中,會看到gameobject一個個加載並顯示在屏幕中,並不會影響到遊戲操做。代碼還須要進一步完善適合更多的資源類型,如動畫資源,文本,字體,圖片和聲音資源。 

動態加載資源除了網絡遊戲必需,對於大公司的遊戲開發也是必須的。它可讓遊戲策劃(負責場景設計),美工和程序3個角色獨立出來,極大提升開發效率。試想若是策劃改變了什麼NPC的位置,美工改變了某個動畫,或者改變了某個程序,你們都要從新倒入一遍資源是多麼低效和麻煩的一件事。ui

相關文章
相關標籤/搜索