Mouse input
- Game Development course
- Beginner
- Lesson 45/83
- 4 min
Learn Input.GetMouseButton and mouse position.
Mouse Buttons: GetMouseButton
In Unity, Input.GetMouseButton and its variants are used to detect mouse clicks. A button index is passed as a parameter: 0 for left mouse button, 1 for right mouse button, and 2 for middle mouse button (scroll wheel). For instance, to catch the first frame of a left-click, call Input.GetMouseButtonDown(0).
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Left mouse button clicked!");
}Mouse Position: Input.mousePosition
The Input.mousePosition property returns the current pixel coordinates of the mouse on screen as a Vector3. The bottom-left corner of the screen is at coordinates (0, 0). This value is frequently used for user interface (UI) interactions or aiming toward the cursor.
Vector3 mousePos = Input.mousePosition;
Debug.Log("Mouse X: " + mousePos.x);Practice Detect Left Mouse Click
If Input.GetMouseButtonDown(0) is true, execute Debug.Log("Ates edildi");.
Starter code
using System;
public static class Input
{
public static bool GetMouseButtonDown(int button) => button == 0;
}
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
// 0 nolu fare tusuna basildiginda "Ates edildi" yazdir
}
}Sample solution
using System;
public static class Input
{
public static bool GetMouseButtonDown(int button) => button == 0;
}
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Ates edildi");
}
}
}Expected output
Ates edildi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which index number represents the right mouse button in Unity?
- 0
- 2
- -1
- 1 Correct answer
Explanation: In mouse buttons, 0 is left button, 1 is right button, and 2 is middle scroll wheel button.
2 Left Click Check
if (Input.____(0))
if (Input.GetMouseButtonDown(0))
Explanation: To detect the initial frame the left mouse button is pressed, GetMouseButtonDown(0) is used.
3 Mouse Inputs Matching
| Term | Meaning |
|---|---|
0 |
Left mouse button index |
1 |
Right mouse button index |
2 |
Middle mouse wheel button index |
Input.mousePosition |
Mouse pixel coordinates on the screen |