【发布时间】:2016-08-13 19:56:22
【问题描述】:
基本上,我正在尝试使用 TextAsset 填充字典,但在此过程中,我不断收到“IndexOutOfRangeException:数组索引超出范围”。来自其中一个阵列,我不知道为什么......我在 Unity 5 中使用 Visual Studio 社区,而且,我只是在 4 个月前才开始学习编程,老实说不知道可能是什么问题。 ..
public Dictionary<string, string> Items = new Dictionary<string, string>();
Start(){
var itemList = Resources.Load("ItemList", typeof(TextAsset)) as TextAsset;
//populating the Dictionaries using previous text assets. Line by Line.
//Populating Dictionary with Text Asset with format Item:Id. The ':' symbol separates lines into columns
string[] rows = itemList.text.Split('\n');
foreach (string row in rows)
{
string[] data = row.Split(':');
Items.Add(data[0].Trim(), data[1].Trim()); //exception is thrown in this line
}
}
ItemList.txt 有这些测试行:
Health Potion:1
Mana potion:2
Beet:3
Poisonous Beet:4
Cheese Slice:5
另一件事是,Visual Studio 一直在 text.Split 行中用波浪线在 itemList (TextAsset) 下划线并显示工具提示:可能的 System.NullReferenceException。但是 unity 根本没有显示任何关于 null 引用的错误。
无论如何,任何建议都将不胜感激。
【问题讨论】:
-
在调试器中抛出异常的行放置一个断点并运行您的应用程序。我敢打赌
data的元素少于 2 个。这是因为至少一个row不包含:。在调试器中查看itemList的内容。 -
嘿,谢谢!没想到这么简单,因为最后有一个空行!但是,无论如何,有没有办法解决这个问题?让代码忽略空行?猜猜,我得去论坛看看,否则我会因为“背负式”问题而被骂。无论如何,谢谢。
标签: c# arrays dictionary split