使用dictionary的add() 方法添加数据,发生数据覆盖。。。。

KEEP GROWING 2017-07-24 07:42:42
希望高手指点迷津。。。。。没找到解决的办法,谢谢了

相关代码:


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


//把text中的内容读取到程序中
public void ReadText(){
//取出文本文件中所有的字符
string text = objectsInfoListText.text;
string[] strArray = text.Split ('\n');//取出一行

ObjectInfo info = new ObjectInfo();

foreach (string str in strArray) {//解析出单独一行的信息
string[] proArray = str.Split (',');
//把属性取出来
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;
print ("现在要添加objectInfo 中 的 icon_name 是 "+ info.id +info.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);//把已经提取出的信息存到字典里,方便调用

//测试代码
foreach (KeyValuePair <int ,ObjectInfo> temp in objectInfoDict){
print ("添加过程中对字典的遍历 " + "键是 " + temp.Key +"值部分 " + temp.Value.id+ temp.Value.icon_name );



}

}
}


测试的信息:

...全文
1147 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
随幻 2017-09-24
  • 打赏
  • 举报
回复
前面已经说对了 最后结果是好多个 Id 对应最后一个物体
LoveMollyWendy 2017-09-18
  • 打赏
  • 举报
回复
ObjectInfo info = new ObjectInfo(); 你确定位置放对地方,你循环操作的有意义?都是一个对象,值肯定一样的
bbs83663622 2017-09-14
  • 打赏
  • 举报
回复
你是在遍历外实例化的ObjectsInfo,所以说从头到尾你只是实例化了一个ObjectsInfo,字典就像是一个冰箱,你实例化的ObjectsInfo就是一个杯子,ObjectsInfo里面的字段就是那你往杯子里装的东西,你不断对杯子里的东西进行替换,最后放进冰箱里的还是只有一只杯子
zgycsmb 2017-08-19
  • 打赏
  • 举报
回复
光这些代码,看不出什么情况
漂亮的石头 2017-07-30
  • 打赏
  • 举报
回复
ObjectInfo info = new ObjectInfo(); 这句话在 循环外边 进行了实例化. 应该 在循环外声明变量, 循环里进行实例化. 在循环里病没有 实例化.每次都是对同一个对象进行修改, 这样改一下. ObjectInfo info = null; foreach (string str in strArray) {//解析出单独一行的信息 info = new ObjectInfo(); string[] proArray = str.Split (','); .......
KEEP GROWING 2017-07-30
  • 打赏
  • 举报
回复
不同的id 下放不同的图片,现在的错误是:从字典里取值时,键不同,但值一样。 发现错误源头是:向字典中添加数据时,每添加一条新的就会覆盖已存在的值(两者id 不同)。。。。。
Moyiii 2017-07-27
  • 打赏
  • 举报
回复
这没太理解你得意思,是不是说读取出来的道具id一样的,只更改数据呢,这样的话,你最好先检测这个id是不是存在于字典里,如果存在就增加数量,否则就增加id 假设你得道具为id, num if (!dic.containsKey(id)) dic.add(id, 0); dic[id] += num

2,535

社区成员

发帖
与我相关
我的任务
社区描述
Unity3D相关内容讨论专区
游戏unity 技术论坛(原bbs)
社区管理员
  • Unity3D
  • 芝麻粒儿
  • 「已注销」
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

Unity3D社区公告:

  1. 社区致力于解决各种Unity3D相关的“疑难杂症”。
  2. 社区不允许发布与Unity3D或相关技术无关内容。
  3. 社区版主邀请各位一道为打造优秀社区不懈努力。

试试用AI创作助手写篇文章吧