Mouse Buttons
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 15 of 67.
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
EasyEach click on the game makes the cube grow by 0.25 on every axis, until it reaches size 2. After that, clicks do nothing. Holding the button down counts as one click.
The cube's size is transform.localScale, and it starts at 1 on every axis. Press Play and click the game, then press 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.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon