Menu
CoddyTech

Pressed, Held, Released

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 12 of 67.

Unity can tell you three different things about a key, and each one is asked in Update():

  • Input.GetKeyDown(KeyCode.Space): was Space pressed on this frame? It is true on one frame per press.
  • Input.GetKey(KeyCode.Space): is Space down right now? It is true on every frame while Space is held.
  • Input.GetKeyUp(KeyCode.Space): was Space released on this frame? It is true on one frame, when the key comes up.

Hold Space for half a second at 60 frames a second, and GetKey is true on 30 frames, GetKeyDown on the first of them, and GetKeyUp on the frame after the last. A cannon that fires once per press asks GetKeyDown; with GetKey, one press would fire 30 shots:

public int shots = 0;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        shots++;
        Debug.Log("Shots fired: " + shots);
    }
}

GetKeyUp is for what happens when the player lets go, such as a sprint that ends. All three answer for the current frame only, which is why they belong in Update(): it runs on every frame, while Start() runs once and would miss nearly every press.

challenge icon

Challenge

Easy

The slingshot charges while Space is held: charge grows by 1 for every second Space is held, and does not grow while it is not. When Space is released, log Charge: followed by the charge (for example Charge: 1.5), then set charge back to 0 for the next shot.

Press Play, hold and release Space, and watch the Console. Then press Check.

Try it yourself

using UnityEngine;

public class Slingshot : MonoBehaviour
{
    float charge = 0f;

    void Update()
    {
        // While Space is held: charge grows by 1 every second.
        // When Space is released: log the charge, then set it back to 0.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics