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

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.7%
  2. Sorry, i don't know either.

    55 vote(s)
    87.3%
  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,495
    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,755
    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