原文:http://zijan.iteye.com/blog/911102
用Unity3D制作基於web的網絡游戲,不可避免的會用到一個技術-資源動態加載。比如想加載一個大場景的資源,不應該在游戲的開始讓用戶長時間等待全部資源的加載完畢。應該優先加載用戶附近的場景資源,在游戲的過程中,不影響操作的情況下,后台加載剩余的資源,直到所有加載完畢。
本文包含一些代碼片段講述實現這個技術的一種方法。本方法不一定是最好的,希望能拋磚引玉。代碼是C#寫的,用到了Json,還有C#的事件機制。
在講述代碼之前,先想象這樣一個網絡游戲的開發流程。首先美工制作場景資源的3D建模,游戲設計人員把3D建模導進Unity3D,托托拽拽編輯場景,完成后把每個gameobject導出成XXX.unity3d格式的資源文件(參看BuildPipeline),並且把整個場景的信息生成一個配置文件,xml或者Json格式(本文使用Json)。最后還要把資源文件和場景配置文件上傳到服務器,最好使用CMS管理。客戶端運行游戲時,先讀取服務器的場景配置文件,再根據玩家的位置從服務器下載相應的資源文件並加載,然后開始游戲,注意這里並不是下載所有的場景資源。在游戲的過程中,后台繼續加載資源直到所有加載完畢。
一個簡單的場景配置文件的例子:
MyDemoSence.txt
- {
- "AssetList" : [{
- "Name" : "Chair 1",
- "Source" : "Prefabs/Chair001.unity3d",
- "Position" : [2,0,-5],
- "Rotation" : [0.0,60.0,0.0]
- },
- {
- "Name" : "Chair 2",
- "Source" : "Prefabs/Chair001.unity3d",
- "Position" : [1,0,-5],
- "Rotation" : [0.0,0.0,0.0]
- },
- {
- "Name" : "Vanity",
- "Source" : "Prefabs/vanity001.unity3d",
- "Position" : [0,0,-4],
- "Rotation" : [0.0,0.0,0.0]
- },
- {
- "Name" : "Writing Table",
- "Source" : "Prefabs/writingTable001.unity3d",
- "Position" : [0,0,-7],
- "Rotation" : [0.0,0.0,0.0],
- "AssetList" : [{
- "Name" : "Lamp",
- "Source" : "Prefabs/lamp001.unity3d",
- "Position" : [-0.5,0.7,-7],
- "Rotation" : [0.0,0.0,0.0]
- }]
- }]
- }
AssetList:場景中資源的列表,每一個資源都對應一個unity3D的gameobject
Name:gameobject的名字,一個場景中不應該重名
Source:資源的物理路徑及文件名
Position:gameobject的坐標
Rotation:gameobject的旋轉角度
你會注意到Writing Table里面包含了Lamp,這兩個對象是父子的關系。配置文件應該是由程序生成的,手工也可以修改。另外在游戲上線后,客戶端接收到的配置文件應該是加密並壓縮過的。
主程序:
- 。。。
- public class MainMonoBehavior : MonoBehaviour {
- public delegate void MainEventHandler(GameObject dispatcher);
- public event MainEventHandler StartEvent;
- public event MainEventHandler UpdateEvent;
- public void Start() {
- ResourceManager.getInstance().LoadSence("Scenes/MyDemoSence.txt");
- if(StartEvent != null){
- StartEvent(this.gameObject);
- }
- }
- public void Update() {
- if (UpdateEvent != null) {
- UpdateEvent(this.gameObject);
- }
- }
- }
- 。。。
- }
這里面用到了C#的事件機制,大家可以看看我以前翻譯過的國外一個牛人的文章。C# 事件和Unity3D
在start方法里調用ResourceManager,先加載配置文件。每一次調用update方法,MainMonoBehavior會把update事件分發給ResourceManager,因為ResourceManager注冊了MainMonoBehavior的update事件。
ResourceManager.cs
- 。。。
- private MainMonoBehavior mainMonoBehavior;
- private string mResourcePath;
- private Scene mScene;
- private Asset mSceneAsset;
- private ResourceManager() {
- mainMonoBehavior = GameObject.Find("Main Camera").GetComponent<MainMonoBehavior>();
- mResourcePath = PathUtil.getResourcePath();
- }
- public void LoadSence(string fileName) {
- mSceneAsset = new Asset();
- mSceneAsset.Type = Asset.TYPE_JSON;
- mSceneAsset.Source = fileName;
- mainMonoBehavior.UpdateEvent += OnUpdate;
- }
- 。。。
在LoadSence方法里先創建一個Asset的對象,這個對象是對應於配置文件的,設置type是Json,source是傳進來的“Scenes/MyDemoSence.txt”。然后注冊MainMonoBehavior的update事件。
- public void OnUpdate(GameObject dispatcher) {
- if (mSceneAsset != null) {
- LoadAsset(mSceneAsset);
- if (!mSceneAsset.isLoadFinished) {
- return;
- }
- //clear mScene and mSceneAsset for next LoadSence call
- mScene = null;
- mSceneAsset = null;
- }
- mainMonoBehavior.UpdateEvent -= OnUpdate;
- }
OnUpdate方法里調用LoadAsset加載配置文件對象及所有資源對象。每一幀都要判斷是否加載結束,如果結束清空mScene和mSceneAsset對象為下一次加載做准備,並且取消update事件的注冊。
最核心的LoadAsset方法:
- private Asset LoadAsset(Asset asset) {
- string fullFileName = mResourcePath + "/" + asset.Source;
- //if www resource is new, set into www cache
- if (!wwwCacheMap.ContainsKey(fullFileName)) {
- if (asset.www == null) {
- asset.www = new WWW(fullFileName);
- return null;
- }
- if (!asset.www.isDone) {
- return null;
- }
- wwwCacheMap.Add(fullFileName, asset.www);
- }
- 。。。
傳進來的是要加載的資源對象,先得到它的物理地址,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方法:
- 。。。
- if (asset.Type == Asset.TYPE_JSON) { //Json
- if (mScene == null) {
- string jsonTxt = mSceneAsset.www.text;
- mScene = JsonMapper.ToObject<Scene>(jsonTxt);
- }
- //load scene
- foreach (Asset sceneAsset in mScene.AssetList) {
- if (sceneAsset.isLoadFinished) {
- continue;
- } else {
- LoadAsset(sceneAsset);
- if (!sceneAsset.isLoadFinished) {
- return null;
- }
- }
- }
- }
- 。。。
代碼能夠運行到這里,說明資源都已經下載完畢了。現在開始加載處理資源了。第一次肯定是先加載配置文件,因為是Json格式,用JsonMapper類把它轉換成C#對象,我用的是LitJson開源類庫。然后循環遞歸處理場景中的每一個資源。如果沒有完成,返回null,等待下一幀處理。
繼續LoadAsset方法:
- 。。。
- else if (asset.Type == Asset.TYPE_GAMEOBJECT) { //Gameobject
- if (asset.gameObject == null) {
- wwwCacheMap[fullFileName].assetBundle.LoadAll();
- GameObject go = (GameObject)GameObject.Instantiate(wwwCacheMap[fullFileName].assetBundle.mainAsset);
- UpdateGameObject(go, asset);
- asset.gameObject = go;
- }
- if (asset.AssetList != null) {
- foreach (Asset assetChild in asset.AssetList) {
- if (assetChild.isLoadFinished) {
- continue;
- } else {
- Asset assetRet = LoadAsset(assetChild);
- if (assetRet != null) {
- assetRet.gameObject.transform.parent = asset.gameObject.transform;
- } else {
- return null;
- }
- }
- }
- }
- }
- asset.isLoadFinished = true;
- return asset;
- }
終於開始處理真正的資源了,從緩存中找到www對象,調用Instantiate方法實例化成Unity3D的gameobject。UpdateGameObject方法設置gameobject各個屬性,如位置和旋轉角度。然后又是一個循環遞歸為了加載子對象,處理gameobject的父子關系。注意如果LoadAsset返回null,說明www沒有下載完畢,等到下一幀處理。最后設置加載完成標志返回asset對象。
UpdateGameObject方法:
- private void UpdateGameObject(GameObject go, Asset asset) {
- //name
- go.name = asset.Name;
- //position
- Vector3 vector3 = new Vector3((float)asset.Position[0], (float)asset.Position[1], (float)asset.Position[2]);
- go.transform.position = vector3;
- //rotation
- vector3 = new Vector3((float)asset.Rotation[0], (float)asset.Rotation[1], (float)asset.Rotation[2]);
- go.transform.eulerAngles = vector3;
- }
這里只設置了gameobject的3個屬性,眼力好的同學一定會發現這些對象都是“死的”,因為少了腳本屬性,它們不會和玩家交互。設置腳本屬性要復雜的多,編譯好的腳本隨着主程序下載到本地,它們也應該通過配置文件加載,再通過C#的反射創建腳本對象,賦給相應的gameobject。
最后是Scene和asset代碼:
- public class Scene {
- public List<Asset> AssetList {
- get;
- set;
- }
- }
- public class Asset {
- public const byte TYPE_JSON = 1;
- public const byte TYPE_GAMEOBJECT = 2;
- public Asset() {
- //default type is gameobject for json load
- Type = TYPE_GAMEOBJECT;
- }
- public byte Type {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Source {
- get;
- set;
- }
- public double[] Bounds {
- get;
- set;
- }
- public double[] Position {
- get;
- set;
- }
- public double[] Rotation {
- get;
- set;
- }
- public List<Asset> AssetList {
- get;
- set;
- }
- public bool isLoadFinished {
- get;
- set;
- }
- public WWW www {
- get;
- set;
- }
- public GameObject gameObject {
- get;
- set;
- }
- }
代碼就講完了,在我實際測試中,會看到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(); } } }