Alvaro Urrutia Alvaro Urrutia - 3 months ago 20
C# Question

Array index out of range when filling a Dictionary using text.Split

Basically I'm trying to fill a Dictionary using a TextAsset, but in the process I keep getting an "IndexOutOfRangeException: Array index is out of range." from one of the arrays and I'm not sure why... I'm using Visual studio Community in Unity 5, also, I've only started learning programming like 4 months ago and honestly have no clue what might be the problem...

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 has these test lines:

Health Potion:1
Mana potion:2
Beet:3
Poisonous Beet:4
Cheese Slice:5


Another thing is, Visual studio keeps underlining itemList (TextAsset) with a squiggly line in the text.Split line and showing the tooltip: Possible System.NullReferenceException. But unity doesn't show any errors regarding null References at all.

Anyway, any advice would be greatly appreciated.

Answer

Use this:

public Dictionary<string, int> Items = new Dictionary<string, int>();
...
string[] rows = itemList.text.Split('\n');
foreach (string row in rows)
{
    string[] data = row.Split(':');
    int i;
    if (data.Length > 1 && int.TryParse(data[1].Trim(), out i))
        Items.Add(data[0].Trim(), i);
}
Comments