- Home /
increasing or decreasing i in a for loop depending on value x?
So, lets say I have this for loop. i will be the counter and x will be the max value to count towards.
The main problem is that i can be higher or lower than x, and rather than counting up or down, it should count towards x, much like mathf.lerp does.
I know I could use a couple of if statements to determine whether i is higher or lower than x, then use 2 different for loops for those 2 scenarios, but this seems very messy. Is there a more elegant way of doing this?
A nice way to go through all elements in a 2D array that are in a rectangular path between point a and b would work too, as that is what I'm trying to use it for.
I'm probably overthinking the problem here so there might be some super easy way to do this that I just can't seem to think of, haha.
Answer by dannyskim · Sep 11, 2013 at 10:03 PM
Here's my solution. As a note, your question really isn't Unity specific.
int incrementer = startValue > stopValue ? -1 : 1;
for( int i = startValue; i != stopValue; i += incrementer ) {
// Code goes here
}
Ah that might work, thanks! The question might not seem very Unity specific, but I've seen plenty answers to questions I had where there was some sort of inbuilt unity function that did exactly what I(or other people, for that matter) wanted. So I thought I might as well ask.
Glad I could help. And given the fact that I answered your question anyway should show you that I get your point =p.
o.o I found a little problem with this tho, not sure if it is an android problem, as it only happens with the remote app running, but Unity freezes when I try to end the for loop by using
i = stopValue;
inside an if statement in the loop.
When not using the remote app this seems to run fine, but with the remote app running it freezes much like a while loop in update does.
Strange thing is tho, that I don't call the function containing this code anywhere on startup, only on specific input. So why it freezes Unity on startup is beyond me o.o