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
MediumThe 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
crouchunits down, andSetis logged. - When Space comes back up after that, the runner stands up again (
crouchunits up),Go!is logged and the run starts: from then on it runs along +z atspeedunits per second. - Holding Space logs
Setonce, 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.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap