0
0
UnityHow-ToBeginner ยท 3 min read

How to Detect Mouse Click in Unity: Simple Guide

In Unity, you detect a mouse click using Input.GetMouseButtonDown(0) inside the Update() method. This checks if the left mouse button was pressed during the current frame.
๐Ÿ“

Syntax

The main method to detect mouse clicks in Unity is Input.GetMouseButtonDown(int button). The button parameter specifies which mouse button to check: 0 for left, 1 for right, and 2 for middle button.

This method returns true only during the frame the button is pressed.

csharp
void Update() {
    if (Input.GetMouseButtonDown(0)) {
        // Left mouse button clicked
    }
}
๐Ÿ’ป

Example

This example shows how to detect a left mouse click and print a message to the console.

csharp
using UnityEngine;

public class MouseClickDetector : MonoBehaviour {
    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            Debug.Log("Left mouse button clicked!");
        }
    }
}
Output
Left mouse button clicked! (printed in Unity Console each time you click left mouse button)
โš ๏ธ

Common Pitfalls

  • Using Input.GetMouseButton instead of Input.GetMouseButtonDown will detect if the button is held down, not just clicked.
  • Placing the check outside Update() will not work because input must be checked every frame.
  • Confusing button numbers: 0 is left, 1 is right, 2 is middle mouse button.
csharp
/* Wrong way: Detects holding mouse button, not click */
void Update() {
    if (Input.GetMouseButton(0)) {
        Debug.Log("Mouse button held down");
    }
}

/* Right way: Detects click only once per press */
void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("Mouse button clicked");
    }
}
๐Ÿ“Š

Quick Reference

MethodDescriptionButton Number
Input.GetMouseButtonDown(button)Detects mouse button pressed this frame0 = Left, 1 = Right, 2 = Middle
Input.GetMouseButton(button)Detects mouse button held down0 = Left, 1 = Right, 2 = Middle
Input.GetMouseButtonUp(button)Detects mouse button released this frame0 = Left, 1 = Right, 2 = Middle
โœ…

Key Takeaways

Use Input.GetMouseButtonDown(0) inside Update() to detect left mouse clicks.
Check input every frame in Update() for accurate detection.
Remember button numbers: 0 = left, 1 = right, 2 = middle mouse button.
Input.GetMouseButtonDown triggers once per click, unlike GetMouseButton which triggers while held.
Use Debug.Log to verify mouse click detection during development.