How to detect when a key is held down?

Here is my code:

using System.Connections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class player : MonoBehavior
{
    Vector3 tempPos;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        // Player movment
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
        tempPos = transform.position;
        float speed = 0.3f;
        tempPos.x += speed;
        transform.position = tempPos;
       }
    }
}
1 Like

if (Input.GetKey(KeyCode.RightArrow))

8 Likes

Thank you

3 Likes

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.

17 Likes

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.

5 Likes

Yeah i know it will only run only be guaranteed to run forever in the Update()

I see you tried to make player movement so here is the code for it
void Update()
{
var speed = 20;
var jumpforce = 50;
if (Input.GetKey(KeyCode.D))
{
Vector2 right = new Vector2 (1,0);
transform.Translate(right * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
Vector2 left = new Vector2 (-1,0);
transform.Translate(left * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Space))
{
Vector2 jump = new Vector2 (0,1);
transform.Translate(jump * jumpforce * Time.deltaTime);
}
}

paste this instead of void Update()

Hi,
Please don’t necro post .
Create a new thread to ask your question and please use code tags.
Thread locked.

1 Like