- Home /
Using a coroutine to wait for a button press?
One of the items in the game I'm working on allows you to control the wind. The way it works is you press a button to select the wind power, then the game should continue as normal while it waits for you to specify what direction you want the wind to go in. I figured a coroutine would be the best way of going about it, but for some reason once one of the directional buttons is pressed, the coroutine ends without changing the wind direction. Any help would be greatly appreciated!
IEnumerator Wind(){
do {
if(Input.GetButtonDown("Horizontal")){
windDir = new Vector3(10*Input.GetAxis("Horizontal"),0,0);
isWindy = true;
}
if(Input.GetButtonDown("Vertical")){
windDir = new Vector3(0,0,10*Input.GetAxis ("Vertical"));
isWindy = true;
}
yield return null;
} while (!Input.GetButtonDown("Horizontal") && !Input.GetButtonDown("Vertical"));
}
Answer by Owen-Reynolds · Apr 24, 2014 at 12:53 AM
Not sure a coroutine is the best place to check for buttons. Seems too easy to double-read the same button in the normal Update check.
For yours, look at the loop structure. The end and the beginning of all loops always touch. So yours waits for a frame (the yield), quits if a button was pressed, then would process the button. Move the yield to the start of the loop?
But, GetAxis ramps up for how long the button was held. Checking it immediately after the button goes down will give a value close to 0. Unless they held it for a while, let go, and pressed it quickly before it drops much. Seems like maybe you want to wait until they release it, then check getAxis.
Ah, that totally makes sense. I've just started using coroutines, and I'm still getting used to their logic. $$anonymous$$oving the yield to the top made it work, but do you think it would still be better to move it to the update function? Also, I didn't realize that GetAxis had a sliding scale. I just assumed it was -1 or 1... good to know!
$$anonymous$$y thinking is: Update is already checking for buttons. If this coroutine runs, Update's button check will have to add "if the coroutine isn't running... ." Then maybe some other button cancels wind selection, so it has to kill that coroutine. Ick. Easier to just say waitingForWindDir=false;
GetAxis is a special helpful thing for new users. It's a secret extra var. As you hold the button, it creeps up to 1 (or -1.) When you let go, it falls. It's made specially for smooth characterController speed-up and slow-down.
Your answer
Follow this Question
Related Questions
Wait for button response in coroutine? 2 Answers
shift key input script 6 Answers
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
Is there any function to check how long a button is pressed? 2 Answers
The "GetButtonDown Version" of GetAxis for Analog Sticks 0 Answers