- Home /
Incrementing a string array (c#)
Hello,
I'm working on what will be a universal script for talking to NPCs in my game. The length of the string will be determined in the inspector, as well as any text that will be said will be entered there as well. So what I'm trying to do is make it so that when you press a key (E), it increases the array by 1 (thus changing the text on screen), and when the array reaches its end, I will have it close the text box (that part isn't in yet). So my question is this: how do I increase the array by one? I've looked everywhere for the past hour and have had no luck, even though the answer sounds simple at least. Here's the (relevant) code I'm using:
void OnGUI () {
if(talking == true){
GUI.Box(new Rect(30,30,650,120), "");
GUI.Box(new Rect(40,40,100,100), "faceplate");
GUI.Label (new Rect (150,40,650,120), mainText[0]);
if(Input.GetKeyDown(KeyCode.E)){
for(int i = 0; i <= mainText.Length-1; i++){
//make mainText[] go to the next element in its index
}
}
}
}
I think the answer is very simple, but I really couldn't find anything. Any help is appreciated, thanks
Answer by robertbu · May 23, 2013 at 11:17 PM
First you the Input.GetKeyDown() needs to be in Update(). OnGUI() often gets called multiple times per frame, so you code will advance multiple times. Then you need a variable to keep track of the current message. The restructured code might look like this (untested):
private int iCurr = 0;
Update() {
if(Input.GetKeyDown(KeyCode.E)){
iCurr++;
if (iCurr >= mainText.Length)
talking = false;
}
}
void OnGUI () {
if(talking){
GUI.Box(new Rect(30,30,650,120), "");
GUI.Box(new Rect(40,40,100,100), "faceplate");
GUI.Label (new Rect (150,40,650,120), mainText[iCurr]);
}
}
Ah, I see what you mean. I guess I was just trying to approach it a weird angle. This works pretty efficiently when adapted to what I already had, thanks!
Answer by darthbator · May 23, 2013 at 11:18 PM
You're looking to shift "forward" through the index correct? Not dynamically re size the array? The way I do this is by making a "key" to the array and incramenting over it. In your block here you would want.
mainText[i] or mainText[i + 1] depending on where you want to be in the array in the loop.
Yeah I had been trying putting variations of that (mainText[i]) in there, but I was unable to figure out the proper syntax to have it not spit an error back at me. Robertbu has a good (but similar) alternative.
Thanks for helping
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Need help fixing this script again... Sorry guys. 0 Answers
Flip over an object (smooth transition) 3 Answers
Problem with UI slider to make it increment other variables 1 Answer