本节学习如何通过读取xml配置文件来读取游戏对象的数据。
首先在Assets文件夹下创建一个StreamingAssets文件夹,文件夹名不能变。先建一个monster文件夹,如图:
xml文件内容为:
<?xml version = "1.0"encoding = "UTF-8"?>
<monsters>
<monster maxHip="10"speed="3"name="胶囊怪物"id="0">
<monster maxHip="100"speed="3"name="强盗"id="1">
</monsters>
加载xml路径
var path = Application.StreamingAssetsPath;
newPath = path + "/Monster/monster.xml";
//load.cs
StreamReader sr = new StreamReader(newPath ,Encoding.UTF8);
XmlDocument doc = new XmlDocument();
doc.load(sr);
XmlNodeList nodelist;
nodelist = doc.SelectNodes("/monsters/monster");
for(int i=0;i<nodelist.Count;i++){
XmlNode node = nodelist[i];
int id = int.Parse(node.Attributes["id"].Value);
string name = node.Attributes["name"].Value;
..........
}
静态数据层的保存方式:
class Monster:Monobehavour{
private int speed;
private string name;
public Monster(int s,string n){
speed = s;
name = n;
}
Dictionary<int,Monster> getconfig = new Dictionary<int,Monster>();
public static Get(int id){
Monster mons;
if(getconfig.TryGetValue(id,out mons)){
return mons;
}
}
//通过加载xml,通过id将不同种类的怪物保存在getconfig中。读取的时候只需要调用Monsteer.Get(int id)静态函数,就能得到相应的怪物
}