Menu
CoddyTech

Pressed, Held, Released

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 19 of 85.

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 and reports the shot on release.

  1. In Update(), while Input.GetKey(KeyCode.Space) is true, add Time.deltaTime to charge.
  2. On Input.GetKeyUp(KeyCode.Space), log "Charge: " + charge, then set charge to 0.

Press Play, hold Space and let go: the Console shows a line like Charge: 1.5. Then 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.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground