- Home /
Increment a loop iteration on button press?
you can pause a loop with yeild, how do you pause a loop using a mouse click to increment it?
for (var x = 0; x < 10;)
{
//Do something;
if ( Input.GetKey("mouse 1") )
{
x+=1;
}
}
Answer by Owen-Reynolds · Sep 20, 2012 at 04:21 PM
Most traditional programmers (and I am one) forget that gameEngines are a loop. 9/10ths of what you want to write a loop for, doesn't need one. This is an odd case, since it really does start life as a loop. Original code (I'm guessing):
createStage0 object
for(int i=1;i<end;i++)
build Stage i assuming current stage is i-1
Converted:
Start() { createStage0 object; i=1; }
Update() if(key press && i<end) { do inside of old loop; i++; }
That's probably a mess for a nested loop (update will have to manually reset the vars.) I think this would keep it more "in place," putting in a coroutine to give the ability to delay:
Start() { StartCoroutine( slowLoop() ); }
bool doNext=false;
Update() { if(key press) doNext=true; }
IEnumerator slowLoop() {
for( ... )
for( ...)
while(!doNext) { yield return null; } // <--- delay line
doNext=false; // <-- clear keypress
// rest of loop
Like you said: messy, the structure is everywhere. but it DOES work!
and like I say, if it works; it works.
Thanks Owen.
How do i use that to construct a wall of blocks? the mouse button is converted to a boolean in your code, and i don't see any x+= that would correspond to a kind of increment.
i am but a noob, this is an advanced explanation in note form for advanced people!
could you illustrate this with print(number of mouse presses);
anyway, as you say, loop and mouse button is pretty much incompatible because a loop runs at clock rate and if you ask it to wait for a IO/game event condition at the end of it's routine rather than give it a code to execute it will crash.
so i have to change all my nested loops to if() statements?
anyways, this is as far as i got with the above wall of blocks explanation until i gave up:
function Start() { StartCoroutine( slowLoop() ); }
bool doNext=false;
Update() { if ( Input.Get$$anonymous$$ey("mouse 1") ))doNext=true; }
IEnumerator slowLoop() {
for(var x = 0; x < 10;x+=0 ){
while(!doNext) { yield return null; } // <--- delay line
doNext=false; // <-- clear keypress
// rest of loop
print(x);
}
Your symbols got mangled, but: the "coroutine" trick just adds a delay to a standard loop. Should be no changes from the old loop(s) you had. The last part is just `x++`, same as always.
The trick is that extra `while` loop will freeze it for as many frames as needed, until a click. Just look up "Unity Input" for the syntax. I'm also using C#, so look up javascript syntax for coroutine and yield.
Answer by AlucardJay · Sep 20, 2012 at 04:25 PM
This is most probably incorrect in some way, but for a positive spin on things :
var isMouseDown : boolean = false;
var isLooping : boolean = false;
function Update()
{
if ( Input.GetKeyDown("mouse 1") )
{
isMouseDown = true;
}
else if ( Input.GetKey("mouse 1") )
{
isMouseDown = true;
}
else if ( Input.GetKeyUp("mouse 1") )
{
isMouseDown = false;
}
if ( !isLooping )
{
LoopingStuff();
}
}
function LoopingStuff() // function as Update cannot be a coroutine (is that the right terminology?)
{
isLooping = true;
for (var x = 0; x < 10; x += 0) // I'm a beginner, so wasn't comfortable leaving this empty!
{
//Do something;
if ( isMouseDown )
{
x+=1;
}
else
{
yield;
}
}
isLooping = false;
}
Actually this would work better than the original code with one issue: It looks like you're starting a new coroutine on each Update. Leaving it as a normal function and putting the //Do something inside the if( is$$anonymous$$ouseDown ) would work, but drop the else.
I like to make flip-flops in $$anonymous$$inecraft, too lazy to move from computer xD
I was just working on an edit to address the every update thing, thanks for the heads-up. Have updated the answer. I dunno, it's all funny really.
Hey Thanks $$anonymous$$ $$anonymous$$ay!
it works in a funny way lets say!
i had a go at the example exactly as you typed it using print(x); as the do something! the loop jumps pretty fast to 9 in one mouse press. :D and the entire game freezes due the the yeild i think.
This line works ok also, although it seems to jump by 2-3 increments even with super fast clicks:
var x = 0;
function Update () {
if ( Input.Get$$anonymous$$ey("mouse 1") ) { x+=1; }
print(x);
}
i learnt alot from that code though, it seems like we need to filter the mouse values into just one value, isn't that a step filter :)
oh wow i thought the solution to this question was going to be like 3 lines!
Answer by ryleigh · Sep 20, 2012 at 04:13 PM
Yeah, the loop is going to run through every value of x very quickly, and won't wait for your mouse click.
Just use a variable in your script (an int, initialized to 0). In your Update() function, check for mouse input, and when it happens, increase your variable and //Do something. Then if x is too big, set it back to 0.
The increment is surrounded by an if statement meaning that it will wait for mouse input. Your given solution will only work assu$$anonymous$$g he isn't waiting for the loop to end before executing some other code. Which is usually the point to a loop.
Thanks Owen, $$anonymous$$uuskii, some program$$anonymous$$g environments give you control of loop iterations and don't crash if you make them wait for a condition inside the loop, so you can run the loop using the clock rate/cpu ticks/audio rate/mouse clicks or gui clicks and any other input. Here i wanted defined the iteration of the loop as a mouse click. perhaps you should also give up unity and gain some more generalised knowledge about computing :D
I'm very glad that you're learning about how stuff works under the hood. However I always find it a good idea not to rely on the system fixing your mistakes for you. It's always good to know why something could break your game to reduce stress on the lower systems and help optimize your game a little bit.
Thanks for being a reasonable person and not throwing insults.
Answer by Muuskii · Sep 20, 2012 at 03:40 PM
This is crashing your game isn't it? I'm going to tell you the same thing I tell everyone who crashes their game with a loop and doesn't know why:
Stop using Unity. Go read basic programming books and get a solid foundation of experience under your feet before you go diving into something as complicated as 3D game development.
Only after you can make basic Windows API games will you have enough understanding to get this sort of stuff to work.
For more experienced future researchers getting here from a search engine: Look at coroutines for a solution to this.
not it's not strictly speaking a loop, it's about 5 nested loops and i'm editing the middle loop to wait for a mouse button.
i've alrady built the code to construct a dodecahedron using phi coordinates and nested loops i just want to use a mouse to slow down the process so i see it being built.
Your answer is patronising and unhelpful, i know rather alot about loops, iterations, digital signal processing, control signal order, and IO.
I looked on google for "increment loop on button press/ mouse click" and guess what! one answer for adobe script, no answers for java, c, JS, etc that i could learn from, and so it seemed like a good idea to ask the question as it was so unavailable!
so i wrote the question clearly and briefly, being brief is to save time for anyone reading!
Ya i looked at CoUpdate first to just put a Yeild into it, didnt work either, not having studied CoUpdate isnt a reason to quit unity either.
ins$$anonymous$$d of sounding aloof and grumpy, you should answer something like "the for loop command can't be modified for caveats, you have to use a while command"
is that right?
Well I apologize if you took my answer negatively however please understand that your question had very little information besides "This didn't work" which honestly sounds a lot like someone who doesn't know what they're doing or why a loop that waits for user input in a real time game is a bad idea. Please don't take this personally I really just want to help people NOT get overwhelmed when getting into something over their head.
How did the coroutine research go? Are you using the one from Unify?
I don't understand how you think the difference between a for loop and a while loop is going to change the fact that you have what is essentially an infinite loop.
Remember; user Input is not Updated until you return and let the engine do it's thing.
it's not an infinite loop, it's so obvious that the "end" variable im my example is an integer variable, logically my code reads like
for (var x = 0; x < 8;) {
which means it would stop at 8.
The question is: you can pause a loop with yeild, how do you pause a loop using a mouse click to increment it?
Your answer

Follow this Question
Related Questions
On-screen button press 1 Answer
On button press/hold = input from a keyboard? 1 Answer
Press button to play "Aim" animation without repeating. 2 Answers
90 Degree Smooth Rotate On Button Press 1 Answer
Press Any Key To Continue 0 Answers