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

[Solved] GetKeyUp registering more than once.

Discussion in 'Scripting' started by Zexanima, Aug 9, 2014.

  1. Zexanima

    Zexanima

    Joined:
    Jan 2, 2014
    Posts:
    33
    When using this bit of code.
    Code (CSharp):
    1. if(Input.GetKeyUp("x")){
    2.             Debug.Log("UP");
    3.             dampening = !dampening;
    4.             if(dampening){
    5.                 gameObject.rigidbody.drag = dragAmount;
    6.             } else {
    7.                 gameObject.rigidbody.drag = 0;
    8.             }
    9.         }
    The key will register as 'up' several times on one release of the key. Any idea what might be causing such an issue?
     
  2. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    Depends on where the code is called. Let me guess - OnGUI()? OnGUI is not only called once like Update() - how often exactly depends on the code included in that function.
     
    Magiichan likes this.
  3. Zexanima

    Zexanima

    Joined:
    Jan 2, 2014
    Posts:
    33
    It's called from a function I placed in FixedUpdate
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    The input is updated once per frame. The problem is that FixedUpdate can be called several times per frame, just as it was mentioned for OnGUI. You have to call it in Update to get the correct result.
     
    Zexanima likes this.
  5. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    Could be that this is the same then, depending on your framerate. FixedUpdate() is tied to the physics timing, meaning that if your framerate is lower, FixedUpdate() might be called multiple times during a frame. GetKeyUp() however is only updated once per frame.
     
  6. Zexanima

    Zexanima

    Joined:
    Jan 2, 2014
    Posts:
    33
    Gotcha. I wasn't quite clear on the difference between Update() and FixedUpdate()
     
  7. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    Doc says: You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has pressed the key and released it again.

    Try calling it from Update.