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
EasyEach click grows the cube, up to size 2.
- In
Update(), write anifonInput.GetMouseButtonDown(0) && transform.localScale.x < 2f. - Inside it, add
new Vector3(0.25f, 0.25f, 0.25f)totransform.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
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