Menu
CoddyTech

Pressed This Frame

Part of the Building Real Games section of Coddy's Unity journey. Lesson 45 of 56.

isPressed answers "is it down now?" on every frame of a hold. For something that should happen once per press, a control has two more answers: wasPressedThisFrame is true only on the frame the key or button went down, and wasReleasedThisFrame only on the frame it came back up. They take the place of Input.GetKeyDown and Input.GetKeyUp, and of GetMouseButtonDown and GetMouseButtonUp. This rubber stamp goes down when the mouse button is pressed and lifts when it is let go:

using UnityEngine;
using UnityEngine.InputSystem;

public class Stamp : MonoBehaviour
{
    public float drop = 0.5f;
    private int stamps;

    void Update()
    {
        Mouse mouse = Mouse.current;

        if (mouse.leftButton.wasPressedThisFrame)
        {
            transform.position += Vector3.down * drop;
            stamps++;
            Debug.Log("Stamp " + stamps);
        }
        if (mouse.leftButton.wasReleasedThisFrame)
        {
            transform.position += Vector3.up * drop;
        }
    }
}

A click held for half a second logs Stamp 1 once, moves the stamp down once and back up once. With isPressed in the first if, the same click would log about 30 stamps and sink the stamp 15 units into the desk. Keys work the same way: Keyboard.current.spaceKey.wasPressedThisFrame is true once per press of Space.

challenge icon

Challenge

Medium

The sprinter waits in the starting blocks. Its script has speed (6) and crouch (0.3).

  • When Space goes down, the runner crouches into the blocks: it moves crouch units down, and Set is logged.
  • When Space comes back up after that, the runner stands up again (crouch units up), Go! is logged and the run starts: from then on it runs along +z at speed units per second.
  • Holding Space logs Set once, not once a frame. Once the runner is running, Space does nothing more.

Read Space with Keyboard.current. Press Play, hold Space and let go, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

public class Sprinter : MonoBehaviour
{
    public float speed = 6f;
    public float crouch = 0.3f;

    void Update()
    {
        // Space down: crouch and log Set. Space up: stand, log Go! and run.
    }
}
quiz iconTest yourself

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

All lessons in Building Real Games