Menu
CoddyTech

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 icon

Challenge

Easy

Fix the frog's hop and make it land again.

  1. Press Play: the Console shows an error about the button "Jumpp". Change it to "Jump".
  2. Add a second if on Input.GetButtonUp("Jump") that takes new Vector3(0, hop, 0) away from transform.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

Practice on your own: Unity playground