Array index is out of range?
I have this error and I'm not sure why it occurs. It says IndexOutOfRangeExcepton - Array is out of range.
Here's my code: (it's not the whole code but I'll only show the relevant code)
public int i = 0;
public Plant[] carrotArray;
// Use this for initialization
void Start () {
carrotArray = new Plant[i];
carrotArray[i].GetComponent<SpriteRenderer>().sprite = CS0;
}
public void CarrotClicked ()
{
if (amountCarrots > 0 && amountTurns > 0) {
carrotArray[i] = Instantiate (carrotArray[i], pos, Quaternion.identity) as Plant;
i++;
}
}
And the error references to: carrotArray[i].GetComponent().sprite = CS0; and carrotArray[i] = Instantiate (carrotArray[i], pos, Quaternion.identity) as Plant;
I don't get why this happens, can anyone help me?
Answer by Suddoha · Oct 01, 2015 at 01:51 PM
You have to make sure that the array is properly populated. Either in the inspector or through a script.
Currently, you create a new array in start with 'i' elements, while 'i' is 0 at the time (if you didn't change it in the inspector). So you'll have an array with 0 elements. Even if you populated it through the inspector, this wouldn't have any effect as you have that one line in the Start method which re-assigns the array and does not populate it.
Also, the code you've posted may sooner or later run into another IndexOutOfRange Exception, because you blindly increment i without even checking if that is a valid index.
Answer by NielsvSchooten · Oct 01, 2015 at 02:30 PM
first in your start function you declare the carrotArray and give it a size. Then you try to get elements from the array, while it is empty. The array needs to be filled before you even try to get something from it. try this:
void Start () {
carrotArray = new Plant[1];
carrotArray.Add(new Plant());
carrotArray[0].GetComponent<SpriteRenderer>().sprite = CS0;
}
Answer by DiegoSLTS · Oct 01, 2015 at 02:03 PM
First make sure i is different than 0 at the begining, otherwhise this line:
carrotArray = new Plant[i];
Will create an array of zero elements.
Anyway, the next line will always throw an error for 2 reasons. First, if the array has "i" elements, the valid indexes will go from zero to "i-1", carrotArray[i] is outside the array. Second, the previous line created an empty array of size "i", there are no elements in the array, so you'll try to get a component of a null reference.
carrotArray[i].GetComponent<SpriteRenderer>().sprite = CS0;
Answer by lmstam · Oct 01, 2015 at 03:36 PM
I got it to work, thanks. I just gave the array a value of 100 because it won't go that far anyway. It's a temporary solution but I don't have to show the code (it's for a school project) and I'm fighting a deadline so I'll fix it properly later :)
You might want to consider using a List ins$$anonymous$$d, which abstracts away having to adjust the array size (and tends to be cleaner).