Named Buttons
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 21 of 85.
Besides keys, Unity has buttons: names listed in the Input Manager (Edit, Project Settings, Input Manager), each tied to one or more keys. Input.GetButtonDown("Fire1") asks about the name, not about a key. A new project has these:
"Jump": Space"Fire1": left Ctrl or the left mouse button"Fire2": left Alt or the right mouse button"Submit"and"Cancel": Enter and Escape
Gamepad buttons are tied to the same names, and the keys can be changed in the Input Manager without touching the code. GetButton, GetButtonDown and GetButtonUp work like GetKey, GetKeyDown and GetKeyUp. This blaster logs a shot for every Ctrl press or click:
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Debug.Log("Shot!");
}
}The name is a string, so a misspelled name compiles. Unity looks it up when the line runs, and when no button has that name it throws on every frame: ArgumentException: Input Button Fier1 is not setup. When you see that message, compare the name in your code with the Input Manager's list.
Challenge
EasyFix the frog's hop and make it land again.
- Press Play: the Console shows an error about the button
"Jumpp". Change it to"Jump". - Add a second
ifonInput.GetButtonUp("Jump")that takesnew Vector3(0, hop, 0)away fromtransform.position.
Press Play, hold Space and let go: the frog hops up, then lands. Then Check.
Try it yourself
using UnityEngine;
public class Hopper : MonoBehaviour
{
public float hop = 1.5f;
void Update()
{
if (Input.GetButtonDown("Jumpp"))
{
transform.position += new Vector3(0, hop, 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