標籤:
讀取遊戲資料檔是遊戲並不可少的一個功能,一般我們搭建Unity環境的時候, 我們會準備一些類來負責資料的讀取操作. 我來介紹下我們公司讀檔遇到的問題.
首先是類的介紹
- BaseData 讀檔的父類
- BaseDataManager 讀檔管理類(BaseDataSecondLoad方法中讀取每一個檔)
- xxxx:BaseData 每一個檔對應的操作類
- Load(string filePath) 方法裡面具體怎麼讀每一個檔
=。=來看下我們讀檔操作是怎麼寫的.貌似看起來沒有問題. 如果環境是這樣的Android+檔是在AssetBundle檔案裡面. 很可能因為策劃和程式員的操作當值檔出一定問題, 假設中途有一個檔出錯之後就不在會讀取後面的文檔, 程式員也沒有log可以判斷到底是哪裡出錯了
public IEnumerator BaseDataSecondLoad() { //讀取每一個檔 m_PassiveSkill.Load(ResourceProvider.gameDataPath + "PassiveSkill"); yield return null; m_BasePointExploreEvent.Load(ResourceProvider.gameDataPath + "BasePointExploreEvent"); m_BasePointExploreBoss.Load(ResourceProvider.gameDataPath + "BasePointExploreBoss"); yield return null; //讀取線上獎勵檔 m_OnlinePrize.Load(ResourceProvider.gameDataPath + "OnlinePrize"); yield return null; m_InvitationCodePrizeData.Load(ResourceProvider.gameDataPath + "InvitationCodePrize"); yield return null; }
我接下來就想到把代碼改成這樣
public IEnumerator BaseDataSecondLoad() { try { //讀取每一個檔 m_PassiveSkill.Load(ResourceProvider.gameDataPath + "PassiveSkill"); yield return null; }catch(Exception e) { //我調試的時候就能馬上知道那個表出錯了 Debug.Log("PassiveSkill 讀取錯誤"); } yield return null; try { //讀取每一個檔 m_PassiveSkill.Load(ResourceProvider.gameDataPath + "PassiveSkill"); yield return null; }catch(Exception e) { Debug.Log("PassiveSkill 讀取錯誤"); } yield return null; //xxxx省略}
後來發現遊戲檔至少有100個, 那麼我try-catch要寫100多遍. 我想到了模板設計模式來利用父類簡化try-catch的冗餘.
BaseData定義讀取檔的流程
public class BaseData{ public string table; public void LoadData(string filePath) { try{ LoadDataOption(); }catch(Exception e) { Debug.Log(table + "表讀取錯誤了,請檢查"); } } protected abstract void LoadDataOption();}
每一個檔實現讀取自己檔的方法
//技能表public class SkillBaseData:BaseData{ protected void LoadDataOption(){ //如何讀取每一個檔 }}
BaseDataManager 類BaseDataSecondLoad()方法就不用寫try-catch 100多遍啦
public IEnumerator BaseDataSecondLoad(){ SkillBaseData n = new SkillBaseData(); SkillBaseData.LoadData("路徑"); yield return null;}
項目實戰(讀檔的錯誤捕捉)