0
\$\begingroup\$

There is a code that needs to be invoke each time user pressed specific button in my game. So I used Input.GetKeyDown to achieve that, but some reason, that code invokes multiple times even I keep pressing the button.

After some tests, I figured out this happens a lot when the game has low frame late. In a very laggy moment, GetKeyDown returns true very many times.

void Update() {
    if(Input.GetKeyDown(KeyCode.RightArrow)) {
        print("Pressed");
    }
}

I saw a similar issue in here but couldn't find any related information. https://forum.unity.com/threads/problems-with-input-at-low-framerates.16828/

My game is a very input sensitive game, so my code when the user each time pressed a specific button always invoke when they pressed.

I checked my keyboard is something wrong, but there was no problem with my keyboard.

Why does this happen? According to the Unity doc, it said:

Returns true during the frame the user starts pressing down the key identified by name

If I used wrong way, then how do I check each time user pressed a button?

Using Unity 2019.1.0f2.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I'm not able to reproduce this in Unity 2019.3.13f1. Even deliberately inducing a slowdown to 2 fps, I still get only one message printed for each time I press the key. If I keep the key held, no additional prints occur. If I tap multiple times on a single long frame, the taps appear to get buffered, and handled one-by-one on subsequent frames, but I never gain new key down events this way (though in some cases I do lose one). Can you create a Minimal Complete Verifiable Example that will let us reproduce this problem in a new empty project? \$\endgroup\$
    – DMGregory
    Jun 20 '20 at 12:54
1
\$\begingroup\$

This sounds like a Unity bug, in which case your best bet is to update Unity (why are you using 2019.1.0f2? That's very out of date) and file a bug report if the issue persists.

A possible workaround:

float lastPressedTime = 0;

void Update() {
    if(Input.GetKeyDown(KeyCode.RightArrow) && Time.time != lastPressedTime) {
        print("Pressed");
        lastPressedTime = Time.time;
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .