【Unity3d】【專案學習心得】從資源伺服器下載資源(一)
阿新 • • 發佈:2019-02-10
專案裡面的許多資源都是從資源伺服器載入的,這樣子可以減小客戶端的包大小。
所以我們需要一個專門的類來管理下載資源。
資源分很多型別,如:json表,txt檔案,image檔案,二進位制檔案,UIAtlas圖集,AssetBundle等。
所以,首先建立一個管理資原始檔型別的類LoadFileType。 其中檔案型別可以用列舉來表示,也可以用類成員常量來表示。
此處使用類成員常量:
using UnityEngine; using System.Collections; namespace AssemblyCSharp { public class LoadFileType { public const string IMAGE = "image"; // unity3d檔案格式 public const string UNITY3D = "unity3d"; // 模組資源打包格式 public const string MODULE_RESOURCE = "moduleResource"; public const string BINARY = "binary"; public const string TXT = "txt"; public const string JSON = "json"; // fbx打包的assetBundle格式檔案 public const string FBX = "fbx"; public const string AUDIO = "audio"; // 字型檔案 public const string FONT = "font"; // 二進位制檔案(用於後臺更新) public const string BINARY_BG = "binary_bg"; } }
接下來需要建立一個類,用來管理單個下載任務,unity3d下載都是使用WWW來下載,我們要建立的類需要具有以下功能:
① 使用WWW下載資源。
② 具備委託回撥介面,方便呼叫這個類的物件能夠接收到反饋,初步回撥需要:下載完成後的回撥,出現錯誤的回撥,下載程序的回撥。
③ 超時設定,超過一定時間則被認定下載任務失敗。
④ 除此之外,還需記錄本次下載任務的URL、以及所下載資源的fileType。
根據以上條件,這個類大致為:
// LoadReques.cs
/** * 下載任務 * create by chensh 2014.10.27 10:31 */ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace AssemblyCSharp { public class LoadRequest { public delegate void DownCompleteDelegate(LoadParam param); public delegate void ErrorDelegate(LoadRequest request); public delegate void ProcessDelegate(float processValue, int fileTotalSize = 0); public DownCompleteDelegate completeFunction; public ErrorDelegate errorFunction; public ProcessDelegate processFunction; public const int TIME_OUT_FRAMES = 300; private int _loadTotalFrames = 0; // 載入的總幀數 public bool isTimeOut = false; public bool alreadyDeal = false; public string requestURL; public string fileType; public WWW wwwObject = null; public List<object> customParams = new List<object>(); public int priotiry = LoadPriority.NORMAL; public LoadRequest(string url, object customParam = null, string type = "", DownCompleteDelegate completeFunc = null, ErrorDelegate errorFunc = null, ProcessDelegate processFunc = null) { requestURL = url; fileType = type; completeFunction = completeFunc; if (completeFunc != null) customParams.Add(customParam); if (errorFunc != null) errorFunction = errorFunc; if (processFunc != null) processFunction = processFunc; wwwObject = new WWW(requestURL); wwwObject.threadPriority = ThreadPriority.Normal; } public int loadTotalFrames { get { return _loadTotalFrames; } set { _loadTotalFrames = value; if (_loadTotalFrames > LoadRequest.TIME_OUT_FRAMES) isTimeOut = true; } } } }