- Home /
Split() into a fixed length array?
Ok here's what i'm pulling my hair out for;
DidoID = decryptedData2[0].ToString().Split(";"[0]);
I have an array setup like this. What i've been trying to do is to specify a length for DidoID and fill in the empty space after the Split happens.
For example the Split() gives me 3 items, i need to add 5 more fields as a string ("empty") to make its length 8. Another example would be Split() giving me 6 items and me needing to add 2 fields this time to make it 8.
8 is good. 8 is life :) So anyways. Here's what i've tried:
for (var xa: int = 0; xa < 8 - DidoID.Length; xa++){
DidoID.Add("empty");
}
this gives:
NullReferenceException: Object reference not set to an instance of an object
I have some ideas about possible reasons. Maybe tt could be something about Split() creating a different type of array? Or could it be something i miss in the for loop?
Can any of you guys help me? :) Thank you in advance...
although it's not clear what you're really trying to do (or why), i believe that you're making this more difficult than it needs to be ;)
why not initialize the entire array before splitting the data so any entries not created by the split function will already be initialized? your only problem then will be if the number of strings from the split exceed the limit of your array...
finally, since this question isn't specific to unity, just generic c# code, you might get answers over at stack overflow or similar sites.
Answer by Bunny83 · Jan 01, 2016 at 06:00 PM
Native arrays can't be resized. You can use Array.Resize but it will create a new array anc copy the elements over.
// UnityScript
var length = DidoID.Length;
Array.Resize(DidoID, 8);
for(var i = length; i < 8; i++)
DidoID[i] = "empty"; // init the new elements with an empty string.
Note: Array.Resize takes a ref-parameter so it's able to replace the array you pass in. If you want to pack those steps into a method, that method also needs a ref parameter. I'm not sure if you can actually define ref-parameters in UnityScript. In C# it would look like this:
//C#
public static void ResizeStringArray(ref string[] aArray, int aSize, string aDefaultString)
{
var length = aArray.Length;
Array.Resize(ref aArray, aSize);
for (int i = length; i < aSize; i++)
aArray[i] = aDefaultString;
}
//C#
ResizeStringArray(ref DidoID, 8, "empty");