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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

How to detect when a key is held down?

Discussion in 'Scripting' started by Bigmancozmo, Sep 13, 2020.

?

How to detect when a key is held down?

  1. I can help!

    8 vote(s)
    12.3%
  2. Sorry, i don't know either.

    57 vote(s)
    87.7%
  1. Bigmancozmo

    Bigmancozmo

    Joined:
    Sep 13, 2020
    Posts:
    17
    Here is my code:

    Code (CSharp):
    1. using System.Connections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class player : MonoBehavior
    7. {
    8.     Vector3 tempPos;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.  
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         // Player movment
    20.         if (Input.GetKeyDown(KeyCode.RightArrow))
    21.         {
    22.         tempPos = transform.position;
    23.         float speed = 0.3f;
    24.         tempPos.x += speed;
    25.         transform.position = tempPos;
    26.        }
    27.     }
    28. }
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,498
    if (Input.GetKey(KeyCode.RightArrow))
     
  3. Bigmancozmo

    Bigmancozmo

    Joined:
    Sep 13, 2020
    Posts:
    17
    Thank you
     
    YUSUF9SEVENCAN and adamgolden like this.
  4. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Just want to clarify further:
    • GetKeyDown
      only runs once on the first frame that the key was pressed.
    • GetKeyUp
      only runs once on the frame that the key was released.
    • GetKey
      runs continuously to check if a key is currently pressed down or not.
     
    iiMoRTaL, leomehta4, Gerzent and 7 others like this.
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    And to clarify one more step, the above is ONLY guaranteed to be true in Update().

    It is NOT necessarily true in any other function (such as FixedUpdate())

    @Vryken if you wanna add that to your post I'll just delete mine. I like how yours is nice and boom-boom-boom straight.
     
    Gerzent and Tofally like this.
  6. Bigmancozmo

    Bigmancozmo

    Joined:
    Sep 13, 2020
    Posts:
    17
    Yeah i know it will only run only be guaranteed to run forever in the Update()
     
    Last edited: Sep 27, 2020