Course contentsShow
← Unity Game Development
Lesson 105 of 8282. Scripting and LifecycleFree lesson

Implementing Mouse Click Interactions

Learners will write scripts to detect mouse button states and trigger specific game events based on user interaction.

In this lesson, you will learn how to detect player clicks and trigger specific game events using Unity’s legacy input system.

Understanding the Input Loop

In Unity, user input is processed inside the Update() method. Because Update() runs once every frame, it is the perfect place to check if a player has pressed a mouse button. We use the Input class to poll for these states, specifically looking for the exact moment a button is pressed, held, or released.

Detecting a Click

To check for a mouse click, we use Input.GetMouseButtonDown(). This method requires an integer argument representing the button: 0 for left-click, 1 for right-click, and 2 for the middle button.

Here is a simple script to trigger an event when the player clicks:

using UnityEngine;

public class ClickHandler : MonoBehaviour
{
    void Update()
    {
        // 0 represents the primary (left) mouse button
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("The mouse was clicked!");
            PerformClickAction();
        }
    }

    void PerformClickAction()
    {
        // This is where your custom game logic lives
        transform.localScale *= 1.2f;
    }
}

Why Use GetMouseButtonDown?

It is important to distinguish between the three primary input states:

  • GetMouseButtonDown(0): Returns true only on the single frame the button is pressed. This is ideal for one-time actions like shooting a gun or selecting a unit.
  • GetMouseButton(0): Returns true every frame the button is held down. This is useful for continuous actions, like charging a power meter.
  • GetMouseButtonUp(0): Returns true on the single frame the button is released.

By placing these checks inside Update(), you ensure your game remains responsive to user interaction. You can combine this with GetComponent or Transform operations you have already learned to manipulate your game objects directly through user input.

Key Takeaway: Use Input.GetMouseButtonDown(0) inside the Update loop to capture a single-frame click event, allowing you to trigger specific logic exactly when the player interacts with your game.