NEIL的Unity學習筆記(1) - 前言與讀取xml

前言:
網路上找了很多例子,但其實這些例子往往是不能滿足搜尋者的要求,為什麼? 因為很多例子往往都只是在解釋原理,而我們真正需要的其實是進行實例的方法。而且往往在論壇上開文章詢問時基本都得不到回應,更甚的是信口雌黃,盡說一些含糊不清或荒誕無稽的說話。尤其是在中國地區,會理你的少之有少,有能力卻又懶得寫下文章分享他人。所以寫下以下文章,給自己一個記錄,也給大家一個方便之門。

最後我要謝謝 unity,unity 我愛你。

好,先來簡單簡短的XML讀取方法。話說我第一天上班就先被要求讀取XML,這個簡單的「讀取XML」在當時就擾攘了一整天,為什麼? 因為我就錯在沒有人有特別提點我要處,網路文章字很多很長,卻沒有重點,最後還是自己試了出來。

程式都是C sharp,注意。

首先加入程式庫  
using System.Xml;
//然後超簡單4句!
void Start(){
  XmlDocument xmlDoc = new XmlDocument();//定義xmlDoc
TextAsset t = Resources.Load("xml/effect") as TextAsset ;
//首先先找到文檔,我這個寫法是放在Resources folder(沒有就自己開一個,名字要對), 使用Resources.Load就可以了,直接名稱就好,不用副檔名。
xmlDoc.LoadXml(t.text);
nodeList=xmlDoc.SelectNodes("//effect");
//就是這句當時卡了我半天,因為當時我找到的寫法是"/effect",是單斜線!  不知道是情況不同還是他寫錯,各位可以自行嘗試。
//然後他就會找到<effect> </effect>node 節點中的資料
}

如果XML裡面包了雙節點
<text1>
    <text2>
    </text2>
</text1> 
那就寫成
nodeList=xmlDoc.SelectNodes("//text1/text2");
就可以了
然後把我卡另外半天的東西就是
my_text=nodeList.ChildNodes.InnerText;
因為資料是文字,所以也要以文字化的指令"
InnerText",把資料指定為文字才可以接受。

那基本上去讀一整列的資料我會以以下方法
首先會先開一個global data的script,把monobehaviour 刪去就可

裡面不能有start、update的運行function
再開一個class 或 struct(據說struct快class執行速度30x)
struct  Data{
 string hp;
string mp;
};

struct[]  Data;  //要注意C  # 的array需要指定數量才可以用, 這裡先把他定義為array


TextAsset t = Resources.Load("xml/player_data") as TextAsset ;
xmlDoc.LoadXml(t.text);
XmlNodeList nodeList;
nodeList=xmlDoc.SelectNodes("//data");
Data=new  struct[nodeList.Count] ;// 定義數量
//開始把每個Data項目中的資料分配
for(int i=0;i<nodeList.Count;i++){
Data[i].hp=nodeList[i].ChildNodes[0].InnerText;
Data[i].mp=nodeList[i].ChildNodes[1].InnerText;
}

如果要用class的做法則要配合 list<class>();的做法

格式為

 List<Project_content> P_Contect = new List<Project_content> ();

 P_Contect.Add(new Project_content());
 P_Contect[i].Name = nodeList[i].ChildNodes[1].InnerText;
 P_Contect[i].item1 = nodeList[i].ChildNodes[2].InnerText;
 P_Contect[i].item2 = nodeList[i].ChildNodes[3].InnerText;
 P_Contect[i].item3 = nodeList[i].ChildNodes[4].InnerText;
 P_Contect[i].item4 = nodeList[i].ChildNodes[5].InnerText;
 P_Contect[i].item5 = nodeList[i].ChildNodes[6].InnerText;
 P_Contect[i].Total = nodeList[i].ChildNodes[7].InnerText;
兩者性質有點不同,class比較用於動態輸入,struct用於一次性資料庫輸入

而XML寫入方法還未用到,待以後有用到再寫,完。

留言

這個網誌中的熱門文章

21-5-2021 時空之門CrossGate/魔力寶貝 主線 劇情 - 4000年輪迴的終結

2020-6-19 《XENOBLADE異度神劍》- 善意地阻止你踩雷

2019-10-21 《Dragon Quest勇者鬥惡龍XI S》 評測 - 平淡而完滿