- Home /
How do I reset a for loop variable???
Hello, so I want the following loop every time I call it the l variable to start from 0. But it doesnt, every time I call it it resumes from where it left...
for(var l: int = 0; l < digits.Length; l++){
reverse += digits[l];
}
Any ideas...?
Answer by Commander5518 · Mar 23, 2015 at 06:00 PM
When the loop ends the control variable is forgotten. Therefore you must re declare it to 0 in the for loop
Answer by DiegoSLTS · Mar 24, 2015 at 03:58 PM
"for" loops work exactly the way you want, if you have a function with that code and you call that function 2 times, the for will run from "l = 0" to "l = digits.Length - 1" eacn time. You can add some debug lines to make sure it's working that way, try this:
Debug.Log("for started");
for(var l: int = 0; l < digits.Length; l++){
Debug.Log("l = " + l);
reverse += digits[l];
}
Debug.Log("for finished");
And every time you call the function with that for loop you'll see this output:
for started
l = 0
l = 1
...
l = some value //the "digits" length minus one
for finished
You probably have some other problem in your code that's confusing you.
$$anonymous$$aybe the problem is that the for loop is at the Update function?
That shouldn't be a problem, the Update method finishes before the next call. Share the full script, it's really hard to come up with something with that little code you posted.
Also, I don't understand if you tried or not the "Debug.Log" thing I suggested, what was the output on the console?
Your answer
Follow this Question
Related Questions
Finding nearest object with a certain tag without for loops. 1 Answer
x=x Assignment made to same variable 3 Answers
Having Trouble with this For Loop 1 Answer
JS Loop question 2 Answers
For statement stops function? 1 Answer