1. 程式人生 > >讀取文本信息,拆分文本信息,根據拆分的文本信息保存在字典中

讀取文本信息,拆分文本信息,根據拆分的文本信息保存在字典中

img == ttext collect image string num 讀取文本 add

技術分享

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsInfo : MonoBehaviour {


private Dictionary<int, ObjectInfo> objectInfoDict = new Dictionary<int, ObjectInfo>();//多個物品信息保存在字典中 ObjectInfo是一個類,在下面有定義

public static ObjectsInfo _instance;
public TextAsset objectsInfoListText;//TextAsset:文本資源,把文本指定在這裏

void Awake() {
_instance = this;
ReadInfo();
//print(objectInfoDict.Keys.Count);
}

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‘);////根據回車鍵拆分

foreach(string str in strArray){
string[] proArray = str.Split(‘,‘);//根據逗號拆分
ObjectInfo info = new ObjectInfo();

int id = int.Parse(proArray[0]);
string name = proArray[1];
string icon_name = proArray[2];
string str_type = proArray[3];
ObjectType type = ObjectType.Drug;
switch (str_type)
{
case "Drug":
type = ObjectType.Drug;
break;
case "Equip":
type = ObjectType.Equip;
break;
case "Mat":
type = ObjectType.Mat;
break;

}
info.id = id; info.name = name; ; info.icon_name = icon_name;
info.type = type;
if (type == ObjectType.Drug){
int hp = int.Parse(proArray[4]);
int mp = int.Parse(proArray[5]);
int price_sell = int.Parse(proArray[6]);
int price_buy = int.Parse(proArray[7]);
info.hp = hp; info.mp = mp;
info.price_buy = price_buy; info.price_sell = price_sell;
}
objectInfoDict.Add(id,info);//添加到字典中,id為key,可以很方便根據id查到物品信息


}
}
}


public enum ObjectType {
  Drug,
  Equip,
  Mat
}
public class ObjectInfo {
  public int id;
  public string name;
  public string icon_name;
  public ObjectType type;
  public int hp;
  public int mp;
  public int price_sell;
  public int price_buy;
}

讀取文本信息,拆分文本信息,根據拆分的文本信息保存在字典中