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
EasyThe slingshot charges while Space is held and reports the shot on release.
- In
Update(), whileInput.GetKey(KeyCode.Space)is true, addTime.deltaTimetocharge. - On
Input.GetKeyUp(KeyCode.Space), log"Charge: " + charge, then setchargeto 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground