Menu
CoddyTech

Pressed This Frame

Part of the Building Real Games section of Coddy's Unity journey. Lesson 46 of 60.

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

Start the sprinter on Space: down to crouch, up to run.

  1. In Update(), when !running and Keyboard.current.spaceKey.wasPressedThisFrame: set set, move down crouch, log Set.
  2. When set and wasReleasedThisFrame: clear set, set running, move up crouch, log Go!.
  3. While running, move along +z at speed units a second.

Press Play, hold Space and let go: Set, then Go! in the Console. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

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

    private bool set;
    private bool running;

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

All lessons in Building Real Games

Practice on your own: Unity playground