【发布时间】:2017-03-07 08:48:59
【问题描述】:
我正在开发一个游戏,用户在玩游戏之前选择一个类别。根据选择的类别,此处加载必要的字典是执行此操作的代码
public Text selectedCategory; //contains the text of the selected category
private Dictionary<String,String> wordList = new Dictionary<String,String> (); //holds the dictionary
private string[] wordListArray; //the array the contents of the text file is first loaded to
private TextAsset textAsset; //the text asset to be used
private string category; // the category selected
void Awake(){
category = selectedCategory.text;
textAsset = Resources.Load ("words", typeof(TextAsset)) as TextAsset;
Debug.Log ("Words dictionary is loaded");
wordListArray = textAsset.text.Split (new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
wordList = wordListArray.ToDictionary (s => s);
Debug.Log ("File loaded as dictionary");
}
第一段代码完美运行,但是当我将其更改为
void Awake(){
category = selectedCategory.text;
if (String.Compare(category, "Animals") == 1) {
textAsset = Resources.Load ("animals", typeof(TextAsset)) as TextAsset;
Debug.Log ("Animals dictionary is loaded");
} else {
textAsset = Resources.Load ("words", typeof(TextAsset)) as TextAsset;
Debug.Log ("Words dictionary is loaded");
}
wordListArray = textAsset.text.Split (new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
wordList = wordListArray.ToDictionary (s => s);
Debug.Log ("File loaded as dictionary");
}
我得到错误代码
ArgumentException:字典中已存在具有相同键的元素。 System.Collections.Generic.Dictionary
2[System.String,System.String].Add (System.String key, System.String value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404) System.Linq.Enumerable.ToDictionary[String,String,String] (IEnumerable1 源,System.Func2 keySelector, System.Func2 元素选择器,IEqualityComparer1 comparer) System.Linq.Enumerable.ToDictionary[String,String] (IEnumerable1 源,System.Func2 keySelector, IEqualityComparer1 比较器) System.Linq.Enumerable.ToDictionary[String,String] (IEnumerable1 source, System.Func2 keySelector) GameController.Awake () (在 Assets/Scripts/GameController.cs:127)
【问题讨论】:
-
您的代码似乎没有出现在您的问题中?
-
@Abdul 谢谢我遇到了同样的问题,您的问题帮助我找到了解决方案
-
@Thematkinson 我已经编辑过了...谢谢
标签: c# linq dictionary unity3d