游戏开发学习笔记(六)物品信息的管理及读取

思路:
创建一个类来存储物品的属性
创建一个枚举类来存储物品的类别
创建一个字典来存储信息
读取文本的内容,先按行拆分,再按‘,’拆分
将解读的信息存储到字典中
提供一个方法通过Id从字典中读取信息


在Access文件夹下建立一个Txt文本文件,将物品信息依次输入,保存格式为UTF-8

例如:id 名称 icon名称 出售价 购买价 类型    加血值 加魔法值

注:icon名称是存储在图集中的名称


创建一个空物体,添加脚本ObjectsInfo,编辑脚本

(物品的类型及属性等后期慢慢会添加)

public class ObjectsInfo : MonoBehaviour {

	public static ObjectsInfo _instance;
	public TextAsset objectsInfoListText; 	//获取得到文本文件	

	private Dictionary objectInfoDict = new Dictionary ();		//创建一个字典

	void Awake(){
		_instance = this;
		ReadInfo ();
	}

	//通过Id从字典里查找到信息
	public ObjectInfo GetObjectInfoById(int id){
		ObjectInfo info = null;
		objectInfoDict.TryGetValue (id, out info);
		return info;
	}

	void ReadInfo(){

		string text = objectsInfoListText.text;		//读取文本中的字符
		string[] strArray = text.Split('\n');		//按行拆分字符,存储在strArray字符串中
       // print(strArray[4]);

		foreach (string str in strArray)            //遍历strArry[]字符串
        {
			string[] proArray = str.Split(','); 	//按,拆分字符串
			ObjectInfo info = new ObjectInfo();		//创建一个Info来存储信息

			info.id = int.Parse (proArray [0]);		//取出来的是字符串,用Parse转换为int类型
			info.name = proArray[1];
			info.icon_name = proArray [2];
			info.price_sell = int.Parse(proArray [3]);
			info.price_buy = int.Parse(proArray [4]);
			string str_type = proArray [5];
            
			switch (str_type)
            {
			case "Drug":
				info.type = ObjectType.Drug;
				break;
			case "Equip":
				info.type = ObjectType.Equip;
				break;
			case "Mat":
				info.type = ObjectType.Mat;
				break;
			}

			if (info.type == ObjectType.Drug)
            {
				info.hp = int.Parse(proArray [6]);
				info.mp = int.Parse(proArray [7]);
			}
            else if (info.type == ObjectType.Equip)
            {
				string str_dresstype = proArray [6];
				switch (str_dresstype) {
				case "Headgear":
					info.dress_type = DressType.Headgear;
					break;
				case "Accessory":
					info.dress_type = DressType.Accessory;
					break;
				case "Armor":
					info.dress_type = DressType.Armor;
					break;
				case "Weapon":
					info.dress_type = DressType.Weapon;
					break;
				case "Shoe":
					info.dress_type = DressType.Shoe;
					break;
				}
				info.attack = int.Parse(proArray [7]);
				info.def = int.Parse (proArray [8]);
				info.speed = int.Parse (proArray [9]);
			}

			objectInfoDict.Add (info.id, info);		//将信息存储到字典里,可以通过ID查找到物品的信息
		}
	}



}

public enum ObjectType{
	Drug,
	Equip
}

public enum DressType{
	Headgear,
	Accessory,
	Armor,
	Weapon,
	Shoe
}

//0	1	2	  3	4	5	6	7	   8	 9
//id	名称	icon名称 出售价	购买价 类型    加血值	加魔法值
//id	名称	icon名称	 出售价	购买价 类型    穿戴类型  伤害 	  防御   速度
//创建一个类来储存这些属性
public class ObjectInfo{
	public int id;
	public string name;
	public string icon_name;		//存储在图集的的icon的名称
	public int price_sell;
	public int price_buy;
	public ObjectType type;
	public int hp;
	public int mp;

	public DressType dress_type;
	public int attack;
	public int def;
	public int speed;
	
}


你可能感兴趣的:(《荣耀》)