We use mouse input to let players click or interact with things on the screen. It helps the game know when and where the player clicks.
0
0
Mouse input (GetMouseButton, position) in Unity
Introduction
When you want to detect if the player clicks the left, right, or middle mouse button.
When you need to find the exact position of the mouse pointer on the screen.
When creating interactive menus or buttons that respond to mouse clicks.
When making games that require dragging or aiming with the mouse.
Syntax
Unity
Input.GetMouseButton(int button)
Input.mousePositionInput.GetMouseButton(0) checks if the left mouse button is held down.
Input.mousePosition gives the current position of the mouse in screen pixels.
Examples
This checks if the left mouse button is pressed and prints a message.
Unity
if (Input.GetMouseButton(0)) { Debug.Log("Left mouse button is pressed."); }
This gets the mouse position and prints it as x, y, z coordinates.
Unity
Vector3 mousePos = Input.mousePosition;
Debug.Log("Mouse position: " + mousePos);This checks if the right mouse button is pressed.
Unity
if (Input.GetMouseButton(1)) { Debug.Log("Right mouse button is pressed."); }
Sample Program
This script checks every frame if the left mouse button is pressed. If yes, it prints the mouse position on the screen.
Unity
using UnityEngine; public class MouseInputExample : MonoBehaviour { void Update() { if (Input.GetMouseButton(0)) { Vector3 pos = Input.mousePosition; Debug.Log($"Left click at position: {pos.x}, {pos.y}"); } } }
OutputSuccess
Important Notes
Mouse position is in pixels from the bottom-left corner of the screen.
Use Input.GetMouseButtonDown to detect the exact frame the button was pressed.
Remember to attach the script to an active GameObject in your scene.
Summary
Use Input.GetMouseButton(button) to check if a mouse button is held down.
Use Input.mousePosition to get the current mouse pointer position.
This helps make your game interactive with mouse clicks and movements.