Array Is Out Of Range

I’m using a while loop to find the last open spot in a string array with 10 elements. Since it is an array, I can’t just add a string to the end of it, so what I did was create the array with the max number of spots it can have, and whenever I needed to add a string to it, I would use this code to find the last open spot. I would then make that last open spot part of the array:

void SearchLastSpot () {

 int i = 0;
 bool searchLength = true;
 Debug.Log(i);

 while(searchLength){
 if(userQuotes *== ""){*

searchLength = false;
lastOpenSpot = i;
}else{
searchLength = true;
}
i++;
}
Debug.Log(lastOpenSpot);
}
And later on in the code:
if(GUI.Button(new Rect(Screen.width/2, Screen.height/1.18F, 100, 50), “Done”)){
SearchLastSpot();
userQuotes[lastOpenSpot] = newQuotes;
userTypes[lastOpenSpot] = newQuotesType;
PlayerPrefsX.SetStringArray(“User Quotes”, userQuotes);
PlayerPrefsX.SetStringArray(“User Quote Type”, userTypes);
PlayerPrefs.SetInt(“LastOpenSpot”, lastOpenSpot);
}
So thats how I’m using it. I’m getting an ArrayIndexIsOutOfRange error for the line:
if(userQuotes == “”){
Which makes no sense cause I did a debug and i = 0, and there’s more than 1 element in my array. What am I doing wrong here?

Note that once your string array is already filled, searchLength will never be set to false before you run out of available slots in your array, thus causing your error. You need to make sure you never access elements with an index >= userQuotes.Length, and catch the case where you used up all available spots (because your array is full).

The Debug.Log(i); will of course always print “0”, since you put this line directly after you initialized i with 0.

Concerning your other script posted in the comment, your “i” is not the problem, your “a” is. change the condition to

while(i < wp.Length && a < wp.Length ){

Just use a List.