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*;*

_ carrotArray*.GetComponent().sprite = CS0;_
_
}_
public void CarrotClicked ()
_
{_
_
if (amountCarrots > 0 && amountTurns > 0) {_
carrotArray _= Instantiate (carrotArray, pos, Quaternion.identity) as Plant;
i++;
}
}
And the error references to:_

_carrotArray.GetComponent().sprite = CS0;_
and carrotArray _= Instantiate (carrotArray, pos, Quaternion.identity) as Plant;*
I don’t get why this happens, can anyone help me?_

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.

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;
 }

First make sure i is different than 0 at the begining, otherwhise this line:

carrotArray = new Plant*;*

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 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*.GetComponent().sprite = CS0;*

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 :slight_smile: