I’m having an issue with converting an array of strings into an array of integers.
What I’ve done, is get an array of strings from XML and used Split() to convert that into an array, which gets me the numbers 2,2,2,1 as it should. Then, I’m using this code to loop through each member of the string array and convert it to an integer, to create an integer array.
The following code is in UnityScript.
var movesRow : String;
var movesString : String[];
var moves : int[];
movesRow = EnemyXML.GetValue("enemies>0>enemy>" + i + ">choices>0>_text");
//this gets me a value of "2,2,2,1" as a string.
//this here then splits it up into a string array
movesString = movesRow.Split(','[0]);
//and then prints it, giving a length of 4, as expected
print (movesString.length);
// here's where i loop through them.
for (var a = 0; a < movesString.length; a++){
//this prints each value, 2, 2, 2, 1 as expected.
print(movesString[a]);
//so I assign each value of the string array to the int array, parsing each one
moves[a] = int.Parse(movesString[a]);
}
But I get a nullreferenceexception, on the int.Parse line. I can’t figure quite what’s going wrong here. Any help would be great!
The nullreferenceexception is due to the way arrays function. You can’t assign a value to an entry in the array until you establish the length of the array. Below is a small change to resize the array prior to assigning values:
var movesRow : String;
var movesString : String[];
var moves : int[];
movesRow = EnemyXML.GetValue("enemies>0>enemy>" + i + ">choices>0>_text");
//this gets me a value of "2,2,2,1" as a string.
//this here then splits it up into a string array
movesString = movesRow.Split(','[0]);
// assign a new array
moves = int[movesRow.length];
//and then prints it, giving a length of 4, as expected
print (movesString.length);
// here's where i loop through them.
for (var a = 0; a < movesString.length; a++)
{
//this prints each value, 2, 2, 2, 1 as expected.
print(movesString[a]);
moves[a] = int.Parse(movesString[a]);
}
var movesString : String[];
var moves : int[] = new int[4];
movesRow = EnemyXML.GetValue("enemies>0>enemy>" + i + ">choices>0>_text");
//this gets me a value of "2,2,2,1" as a string.
//this here then splits it up into a string array
movesString = movesRow.Split(','[0]);
//and then prints it, giving a length of 4, as expected
print (movesString.length);
// here's where i loop through them.
for (var a = 0; a < movesString.length; a++){
//this prints each value, 2, 2, 2, 1 as expected.
print(movesString[a]);
//so I assign each value of the string array to the int array, parsing each one
moves[a] = int.Parse(movesString[a]);
}
var moves : int = new int[4]; this here worked, because there can only ever be 4 values that come from the XML. So yes, TrickyHandz was right, the length did need to be set first.