用Unity的TextAsset读取TXT文档内容,将物品信息存入字典中

用Unity的TextAsset读取TXT文档内容,将物品信息存入字典中


Text Asset 文本资源

Text Assets are a format for imported text files. When you drop a text file into your Project Folder, it will be converted to a Text Asset. The supported text formats are:

文本资源是导入的文本文件的一个格式。当你拖入一个文本文件到你的项目时,他会被转换为文本资源。支持的文本格式有:

.txt
.html
.htm
.xml
.bytes

Properties 属性

Text
The full text of the asset as a single string.


物品属性分析

物品属性分析

之后需要新建一个文本txt来存放物品的属性,这里以药品为例

TXT文档内容

TXT文档内容

每一行文本对应一种物品,用逗号分隔,每个值对应属性表里的每一列属性。

之后新建c#脚本解析文本内容

private TextAsset objectsInfoListText; // 新建TextAsset变量
private Dictionary<int, ObjectInfo> objectInfoDict = new Dictionary<int,ObjectInfo>();

void Awake()
{
    objectsInfoListText = Resources.Load("ObjectsInfoList") as TextAsset; // 从Resouces的path中读取到文件
    ReadInfo();
}
void ReadInfo()
{
     string text = objectsInfoListText.text;  // 将文本内容作为字符串读取
     string[] objInfoArray = text.Split('\n'); // 以\n为分割符将文本分割为一个数组
     foreach (string str in objInfoArray)  // 遍历每一行并将每一个药品的值放入类对象中,并存入字典
     {
         ObjectInfo info = new ObjectInfo();
         string[] propertyArray = str.Split(',');
         int id = int.Parse(propertyArray[0]);
         string name = propertyArray[1];
         string icon_name = propertyArray[2];
         string str_type = propertyArray[3];
         ObjectType type = ObjectType.Drug;
         switch (str_type)
         {  
             case "Equip":
                 type = ObjectType.Equip;
                 break;
             case "Mat":
                 type = ObjectType.Mat;
                 break;
             case "Drug":
                 type = ObjectType.Drug;
                 break;
         }

         info.id = id; info.name = name; 
         info.icon_name = icon_name; info.type = type;

         if (type == ObjectType.Drug)
         {
             int hp = int.Parse(propertyArray[4]);
             int mp = int.Parse(propertyArray[5]);
             int price_sell = int.Parse(propertyArray[6]);
             int price_buy = int.Parse(propertyArray[7]);

             info.hp = hp; info.mp = mp; info.price_sell = price_sell; info.price_buy = price_buy;
         }

         // 将物品信息存储到字典中
         objectInfoDict.Add(id, info);
     }
}

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

  • 12
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值