Search Unity

Solution for key holding in new input system

Discussion in 'Input System' started by lifeisabeach, Nov 10, 2020.

  1. lifeisabeach

    lifeisabeach

    Joined:
    Apr 26, 2020
    Posts:
    47
    I need to capture the 'left' and 'right' keyboard keys continuously. Also when both are pressed together, continously. For as long as they are held pressed.

    I am trying to implement this with the new input system for a few days and am having a hard time. It seems like I get more than one event for pressing or releasing.

    My need is so simple I am getting frustrated by not getting it to work. If anyone could help I'd greatly appreciate it.

    What would be a good solution for this need?

    I wish a simple solution like this would work, but it doesn't. I get uneven 'pressed' and 'released' events.

    Code (CSharp):
    1. if (Keyboard.current.spaceKey.wasPressedThisFrame)
    2. {
    3.     Debug.Log("SPACE PRESSED");
    4. }
    5.  
    6. if (Keyboard.current.spaceKey.wasReleasedThisFrame)
    7. {
    8.     Debug.Log("SPACE RELEASED");
    9. }
    I tried creating actions and all that but was getting similar results, and an overkill solution for a simple problem.

    Thanks!
     
  2. monicamark000

    monicamark000

    Joined:
    May 22, 2023
    Posts:
    1
    I understand your frustration with implementing continuous capture of the 'left' and 'right' keyboard keys using the new input system. It seems like you're receiving multiple events for pressing or releasing the keys, which is causing uneven results.

    A good Solution for your need would be to use the Keyboard.current API with the ReadValue() method instead of wasPressedThisFrame and wasReleasedThisFrame. This will give you continuous input as long as the keys are held down. Here's an example:

    CSharp
    void Update()
    {
    if (Keyboard.current.leftKey.ReadValue() > 0)
    {
    Debug.Log("LEFT KEY PRESSED");
    }

    if (Keyboard.current.rightKey.ReadValue() > 0)
    {
    Debug.Log("RIGHT KEY PRESSED");
    }
    }

    By using ReadValue(), you can continuously check if the keys are pressed instead of relying on the "pressed" and "released" events. This should provide a simpler solution for your requirement.