You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Get mouse input in Unity

Ben Liu
Ben Liu

To get the mouse input event in Unity, we have to create a script attached to your game object. Then add the following script to it:

Mouse click

using UnityEngine;
using System.Collections;

// Detects clicks from the mouse and prints a message
// depending on the click detected.

public class ExampleClass : MonoBehaviour
    void Update()
        if (Input.GetMouseButtonDown(0))
            Debug.Log("Pressed left button.");

        if (Input.GetMouseButtonDown(1))
            Debug.Log("Pressed right button.");

        if (Input.GetMouseButtonDown(2))
            Debug.Log("Pressed middle click.");

Mouse scroll

void Update()
    Debug.Log("mouse: " + Input.mouseScrollDelta.y );

If you scroll you mouse up and down, you will get the log like:

mouse: 6.643539
mouse: 12.98123

Ben Liu

Please feel free to contact me if you have any question. <br>