Mouse input in Unity

This tutorial explains how to detect mouse button clicks and mouse movement in your game using a C# script. This will allow your players to interact with the game using their mouse.

Watch the video below and then scroll down to see the sample code.

Mouse button clicks

To detect mouse button clicks, you use the GetMouseButtonDown() method which takes an integer value (between 0 and 2) to specify which mouse button you want to check. 0 is for the left button, 1 is for the right button, and 2 is for the middle button. The method will return a Boolean value indicating whether the specified mouse button has been pressed when using code like the example shown below.

bool isLeftButtonDown = Input.GetMouseButtonDown(0);
bool isRightButtonDown = Input.GetMouseButtonDown(1);
bool isMiddleButtonDown = Input.GetMouseButtonDown(2);

This code will display a message if the left mouse button is pressed:

if(Input.GetMouseButtonDown(0))
{
 print("The left mouse button was pressed");
}

Save the script and then run the scene. Check the output in the console when you click the left mouse button.

Mouse movement

Mouse movement is measured by reading the amount that the mouse has moved since the last frame, across the X and Y axes on screen.

The sample code below will read the mouse movement and display the value in the console. Place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float mouseXValue = Input.GetAxis("Mouse X");
float mouseYValue = Input.GetAxis("Mouse Y");
 
if(mouseXValue != 0)
{
 print("Mouse X movement: " + mouseXValue);
{
 
if(mouseYValue != 0)
{
 print("Mouse Y movement: " + mouseYValue);
{

Save the script and then run the scene. Check the output in the console when you move the mouse around the screen.