Detect which key is pressed in Unity C#?

Hello programmers, In this article, I will show how to “Detect which key is pressed in Unity C#”

Before we get started with the building process, we need to know a few concepts. Let’s first discuss them one by one.

Input.GetKeyDown()

Input.GetKeyDown will return true only once during the frame the user starts pressing down the specific key.

Syntax:-

Input.GetKeyDown(KeyCode.Return)

Input.GetKey()

Input.GetKey will return true continuously while the user holds down the specific key.

Syntax:-

Input.GetKey(KeyCode.Return)

Input.GetKeyUp()

Input.GetKeyUp will return true only once during the frame the user releases the specific key.

Also read:
Detect collision with a specific object in Unity 3D C#

Syntax:-

Input.GetKeyUp(KeyCode.Return)

The below-given program to detect which key is pressed in Unity

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class keypress1 : MonoBehaviour
{

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Return))
        {
            Debug.Log("Enter key is pressed");
        }
        if (Input.GetKey(KeyCode.Return))
        {
            Debug.Log("Enter key is continuously pressed");
        }
        if (Input.GetKeyUp(KeyCode.Return))
        {
            Debug.Log("Enter key is released");
        }

    }
}

Output:-

Detect keypress in unity c#

Leave a Reply

Your email address will not be published. Required fields are marked *