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

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(' ');////根据回车键拆分

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;
}

原文地址:https://www.cnblogs.com/panyuyi/p/6886476.html