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

Bug Input.GetKeyDown isnt working

Discussion in 'Scripting' started by Geniusme56, Apr 20, 2023.

  1. Geniusme56

    Geniusme56

    Joined:
    Aug 21, 2021
    Posts:
    55
    I am trying to make it so that when I press the key "R", it logs r. This is my code:
    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.R))
    2.             {
    3.                 Debug.Log("r");
    4.             }
    My problem is, that when i press "R", most of the time, it doesn't debug. Can anyone help? Thanks!
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,883
    Are you polling this input in
    Update()
    or
    FixedUpdate()
    ? Input should only be polled in the former, not the latter.
     
    Bunny83 and seejayjames like this.
  3. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    685
    When you say "most" it makes me wonder if you're clicking in the game window (after clicking Play) to give it keyboard focus, which it needs. If the last thing you clicked on was a field in the Inspector (or something else), there's your keyboard focus, and the game won't hear any presses, at least that's my recollection when running into this.
     
    Bunny83 likes this.
  4. Geniusme56

    Geniusme56

    Joined:
    Aug 21, 2021
    Posts:
    55
    I am in the game view, and spamming the r button. 1 out of 4 or 5 times it debugs it. Also, it is called in Fixed update, meaning that it cant be the problem.
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,883
    If you read my post again you'll find it's 100% the problem.

    Input should only be polled in
    Update()
    , never in
    FixedUpdate()
    .
     
  6. Geniusme56

    Geniusme56

    Joined:
    Aug 21, 2021
    Posts:
    55
    Oh sorry. Yeah you are right.