把物品信息以及id存入字典并输出,然后报错了:
FormatException: Input string was not in the correct format
System.Int32.Parse (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Int32.cs:629)
ObjectsInfo.ReadInfo () (at Assets/Scripts/Custom/ObjectsInfo.cs:37)
ObjectsInfo.Awake () (at Assets/Scripts/Custom/ObjectsInfo.cs:15)
看字面意思是输入字符串的格式有问题,可是我找了很久都没发现是哪里的问题。
这是我完整的的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectsInfo : MonoBehaviour
{
public static ObjectsInfo _instance;
public TextAsset objectsList;
private Dictionary<int, ObjectInfo> objectInfoDict = new Dictionary<int, ObjectInfo>();//创建一个字典
void Awake()
{
_instance = this;//单例模式
ReadInfo();
print(objectInfoDict.Keys.Count);
}
//根据id得到信息
public ObjectInfo GetObjectInfoById(int id)
{
ObjectInfo info = null;
objectInfoDict.TryGetValue(id, out info);
return info;
}
//读取信息
void ReadInfo()
{
string text = objectsList.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_sell = price_sell;
info.price_buy = price_buy;
}
objectInfoDict.Add(id, info);//添加到字典中,根据id查找物品信息
}
}
}
//id
//名称
//icon名称
//类型(药品Drug、装备Equip、材料Mat)
//加血量值
//加法力值
//出售价
//购买价
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;
}
错误提示中问题所在的15行也是Awake()方法中调用ReadInfo(),37行是int id = int.Parse(proArray[0]);
记事本里既没有多余的空格也没有中文逗号,实在是没办法了,麻烦老师帮忙看下~