Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Reduce Key Inputs to one per push

Discussion in 'Getting Started' started by Fe0dor, Feb 5, 2020.

  1. Fe0dor

    Fe0dor

    Joined:
    Jan 18, 2020
    Posts:
    17
    Hello,

    I'm working on a Game that counts how many steps the player has made. And because the player slides to the next wall with every directional Input.
    The problem is that even If I push and release the key really fast it allready Inputs at least two times.
    That would not be a problem if step counting was'nt a keayfeature but it certainly is.

    I'm currently using Input.getKeyDown("KEY"); but there got to be a far better solution so it inputs just once per push

    Thanks
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,136
    Input.GetKeyDown() only returns a single key press. If you are seeing multiple key presses with it then the function is being called multiple times. Do you have it in FixedUpdate() by any chance?
     
    Fe0dor likes this.
  3. Fe0dor

    Fe0dor

    Joined:
    Jan 18, 2020
    Posts:
    17
    Yeah... is that the Problem?
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,136
    Yes. For starters, everything involving the Input class is updated by Update() once per frame. FixedUpdate() will be run as many times as necessary to keep up with the rate you set it to (eg if you set it to run at 120 FPS and your frame rate is 60 FPS it'll run twice per frame). FixedUpdate() is only intended for physics.
     
    JoeStrout, Joe-Censored and Fe0dor like this.
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Don't use GetKeyDown in FixedUpdate. GetKeyDown returns true on the frame the key was pressed, but FixedUpdate can be called 0 times on that frame or multiple times on that frame. If called 0 times, then you will entirely miss the key press. If called multiple times on that frame then GetKeyDown will return true for all those calls. Only call it from Update or somewhere which is otherwise called exactly once per frame.