Menu
CoddyTech

Mouse Buttons

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 22 of 85.

Mouse buttons have their own three methods, and they take the button's number: 0 is the left button, 1 the right, 2 the middle.

  • Input.GetMouseButtonDown(0): the left button went down on this frame.
  • Input.GetMouseButton(0): it is down right now, on every frame of the hold.
  • Input.GetMouseButtonUp(0): it came up on this frame.

They work like the key methods, and Input.GetMouseButtonDown(0) is the same as Input.GetKeyDown(KeyCode.Mouse0). This bell rings once for every click on the game:

public int rings = 0;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        rings++;
        Debug.Log("Ding! " + rings);
    }
}

A click anywhere on the game counts, not only a click on the bell: these methods report the button, not what is under the pointer. Telling which object was clicked takes more code than this. On a phone, Unity reports a tap as mouse button 0, so the bell rings for taps too.

challenge icon

Challenge

Easy

Each click grows the cube, up to size 2.

  1. In Update(), write an if on Input.GetMouseButtonDown(0) && transform.localScale.x < 2f.
  2. Inside it, add new Vector3(0.25f, 0.25f, 0.25f) to transform.localScale.

Press Play and click the game four times: the cube grows to twice its size and stops. Then Check.

Try it yourself

using UnityEngine;

public class Grower : MonoBehaviour
{
    void Update()
    {
        // Each click: grow by 0.25 on every axis, up to size 2.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground