- Home /
Only KeyPress once?
Whenever I use
if (Input.GetKey(KeyCode.F)){
Debug.Log("F pressed");
blah blah
}
and I press it, it gives the log message like 4 times when I just pressed F once for a really short time. Is there a way to give the message once, no matter how long I hold it down for?
Answer by Jamora · Aug 25, 2013 at 09:18 PM
I assume your script is inside the Update method. That method is run every frame. Combine that with the fact that GetKey returns true every frame the key is held down, you will truly have to press the key fast. (You need to keep it down less than about 0.016sec on 60fps.)
To remedy the situation, use Input.GetKeyDown as that is called only when the key is pressed the first time.
Hi, Im facing the same problem, even I change the method to Input.Get$$anonymous$$eyDown, It still have multi calls when fps is low(less than 20). Can I define a flag to judge only one time of key press in one frame? where can I put this flag? while I m using Fixedupdate()
You could track the last frame or time the key was pressed. This can also be useful if you're trying to control how often a player does an action.
if (m_lastPressed != Time.time) {
m_lastPressed = Time.time;
// Code here.
}
hey, im using on screen buttons . the same happens when i touch a button ( the statements are run multiple times). Is there any feature similar to "getkeydown" which i can use????????????????????
Something like this helped...just in case if you are still looking for answer
void FixedUpdate()
{
transform.position = new Vector3(value, transform.position.y, transform.position.z);
if(Input.GetKeyDown(KeyCode.RightArrow)){
if(value < 2){
value += 2;
}
}
if(Input.GetKeyDown(KeyCode.LeftArrow)){
if(value > -2){
value -= 2;
}
}
}
Your answer
Follow this Question
Related Questions
Catch Ctrl+Z input in Editor 1 Answer
Ensuring that a button is released before checking that it's pressed? 2 Answers
Check the latest key pressed? 2 Answers
Key binding screen 0 Answers
Input.GetKey behaving strangely 2 Answers