- Home /
C# Incrementing a String Array
Hi everyone, is there a way to increment a string array? Every time the MoveUpOne button is pressed I want someString to increment to the next element of the string Array.Can that be done?
public String someString;
public String[] someArray;
void Start(){
someString = someArray[0];
someArray = new string[]{"text","text2","text3"};
}
void OnGUI(){
if (GUILayout.Button("MoveUpOne", GUILayout.Width(50), GUILayout.Height(25))){
//Make someString increment from someArray[0] to someArray[1] and so on
}
}
What do you mean 'increment'? Just assigning a new value to someString
likesomeString = someArray[Array.IndexOf(someArray, someString) + 1]
?
If so, you could just keep an extra index variable at class level and increment that ins$$anonymous$$d of using IndexOf
I tried that but I keep getting this error. Array doesn't exist in current context
Answer by Dave-Carlile · Jan 24, 2013 at 07:53 PM
Keep a separate variable that stores the current index into someArray. Increment that variable, then set someString to the array value at that index.
int someStringIndex;
void OnGUI()
{
if (GUILayout.Button("MoveUpOne", GUILayout.Width(50), GUILayout.Height(25)))
{
someStringIndex++;
someString = someArray[someStringIndex];
}
}
You will need to make sure someStringIndex doesn't go beyond the end of the array.