Mouse input in Unity
3D Game Design with Unity
🕑 This lesson will take about 15 minutes
In this lesson, you will learn 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.
Is YouTube blocked at school? Watch on Google Drive.
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.
This code will display a message if the left mouse button is pressed:
Save the script and then run the scene. Check the output in the Debug 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).
Save the script and then run the scene. Check the output in the Debug console when you move the mouse around the screen.
Next lesson: Working with force and gravity in Unity