- Home /
Trying to see how long the player holds down a key. GetKeyDown & GetKeyUp behaving oddly. (C#)
I'm trying to allow the player to jump higher based on how long he holds down the jump key (to a limit). For now I'm not bothering with the limit just to make sure the code is working, and it's behaving strangely. I can't seem to figure how why it's doing what it's doing. This code is in my Update function:
if(Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)){
jumpButtonDown = true;
Debug.Log("Key Pressed "+jumpButtonDown);
}
if(jumpButtonDown==true){
moveDirection.y+=jumpSpeed;
}
if(Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.UpArrow)){
jumpButtonDown = false;
Debug.Log("Key Released "+jumpButtonDown);
}
So, what happens is that my debug log for the first if statement gets logged in the debugger and then the getKeyUp never triggers and the code in the 2nd if statement repeats on every update forever. However, if I remove the code from the 2nd if statement (and make it just empty), then the getKeyUp will trigger and I'll get the Debug Log message. Any idea why this isn't working? =\
I'd rather work with Get$$anonymous$$ey ins$$anonymous$$d, it is probably much more reliable.
How would I get Get$$anonymous$$ey to work as I want it in this situation? I want to count how many frames a player is holding down a key and do something (push the player up on the Y axis) for each of the frames he's holding down the key.
It might have something to do with the OR on the input. $$anonymous$$aybe try to see if it works with just one of the keys?
Just tried removing the OR on both the keyup and the keydown, same result. :\
I just tested your code in my player and it works. I made the assumption that your boolean (jumpbuttondown) is declared globally, and it works fine:
public class TestGUI : $$anonymous$$onoBehaviour {
bool press;
void Start () {
press=false;
}
void Update () {
if(Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.W)|| Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.UpArrow)){
press=true;
Debug.Log("$$anonymous$$ey pressed");
}
if(Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.W) || Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.UpArrow)){
press= false;
Debug.Log ("$$anonymous$$ey Released");
}
}
}
Answer by Jurassic · Jul 19, 2013 at 09:32 PM
I figured it out! The problem was that my whole jump code was nested inside a giant isGrounded check. So the keyUp was first checking to see if it was grounded, and obviously he wouldn't be if he just jumped, so it would never fire. Lol. Thanks guys!
Answer by Jamora · Jul 19, 2013 at 09:06 PM
I copy-pasted your code and it works perfectly for me.
You must either have your boolean defined inside Update (a local variable; reset every frame), or a null moveDirection, which would cause a null reference exception and break out of your update, never triggering your GetKeyUp.