(轉)在Unity3D的網絡游戲中實現資源動態加載


原文:http://zijan.iteye.com/blog/911102

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

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

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

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

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,這兩個對象是父子的關系。配置文件應該是由程序生成的,手工也可以修改。另外在游戲上線后,客戶端接收到的配置文件應該是加密並壓縮過的。 

主程序: 

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方法: 

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的位置,美工改變了某個動畫,或者改變了某個程序,大家都要重新倒入一遍資源是多么低效和麻煩的一件事。 

======================================================================

生成配置文件代碼

using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Text;
using System.Collections.Generic;
using LitJson;
public class BuildAssetBundlesFromDirectory
{
      static List<JsonResource> config=new List<JsonResource>();
      static Dictionary<string, List<JsonResource>> assetList=new Dictionary<string, List<JsonResource>>();
        [@MenuItem("Asset/Build AssetBundles From Directory of Files")]//這里不知道為什么用"@",添加菜單
        static void ExportAssetBundles ()
        {//該函數表示通過上面的點擊響應的函數
                   assetList.Clear();
                   string path = AssetDatabase.GetAssetPath(Selection.activeObject);//Selection表示你鼠標選擇激活的對象
                  Debug.Log("Selected Folder: " + path);
       
       
                  if (path.Length != 0)
                  {
                           path = path.Replace("Assets/", "");//因為AssetDatabase.GetAssetPath得到的是型如Assets/文件夾名稱,且看下面一句,所以才有這一句。
                            Debug.Log("Selected Folder: " + path);
                           string [] fileEntries = Directory.GetFiles(Application.dataPath+"/"+path);//因為Application.dataPath得到的是型如 "工程名稱/Assets"
                           
                           string[] div_line = new string[] { "Assets/" };
                           foreach(string fileName in fileEntries)
                           {
                                    j++;
                                    Debug.Log("fileName="+fileName);
                                    string[] sTemp = fileName.Split(div_line, StringSplitOptions.RemoveEmptyEntries);
                                    string filePath = sTemp[1];
                                     Debug.Log(filePath);
                                    filePath = "Assets/" + filePath;
                                    Debug.Log(filePath);
                                    string localPath = filePath;
                                    UnityEngine.Object t = AssetDatabase.LoadMainAssetAtPath(localPath);
                                   
                                     //Debug.Log(t.name);
                                    if (t != null)
                                    {
                                            Debug.Log(t.name);
                                            JsonResource jr=new JsonResource();
                                            jr.Name=t.name;
                                            jr.Source=path+"/"+t.name+".unity3d";
                                              Debug.Log( t.name);
                                            config.Add(jr);//實例化json對象
                                              string bundlePath = Application.dataPath+"/../"+path;
                                               if(!File.Exists(bundlePath))
                                                {
                                                   Directory.CreateDirectory(bundlePath);//在Asset同級目錄下相應文件夾
                                                }
                                              bundlePath+="/"  + t.name + ".unity3d";
                                             Debug.Log("Building bundle at: " + bundlePath);
                                             BuildPipeline.BuildAssetBundle(t, null, bundlePath, BuildAssetBundleOptions.CompleteAssets);//在對應的文件夾下生成.unity3d文件
                                    } 
                           }
                            assetList.Add("AssetList",config);
                            for(int i=0;i<config.Count;i++)
                            {
                                    Debug.Log(config[i].Source);
                            }
                  }
                string data=JsonMapper.ToJson(assetList);//序列化數據
                Debug.Log(data);
        string jsonInfoFold=Application.dataPath+"/../Scenes";
        if(!Directory.Exists(jsonInfoFold))
        {
            Directory.CreateDirectory(jsonInfoFold);//創建Scenes文件夾
        }
                string fileName1=jsonInfoFold+"/json.txt";
                if(File.Exists(fileName1))
                {
                    Debug.Log(fileName1 +"already exists");
                    return;
                }
                UnicodeEncoding uni=new UnicodeEncoding();
                  
                using(  FileStream  fs=File.Create(fileName1))//向創建的文件寫入數據
                {
                        fs.Write(uni.GetBytes(data),0,uni.GetByteCount(data));
                        fs.Close();
                }
      }
}

 


免責聲明!

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



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