mouse click in unity code example

Example 1: how to detect a mouse click in unity

using UnityEngine;
using System.Collections;

		if (Input.GetMouseButtonDown(0)) {
        	//Left Mouse Button
        } else if (Input.GetMouseButtonDown(1)) {
        	//Right Mouse Button
        } if (Input.GetMouseButtonDown(2)) {
        	//Middle Mouse Button
        }

Example 2: unity mouse click position

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit hit = new RaycastHit();

if (Physics.Raycast(ray, out hit))
{
	return hit.point;
}

Example 3: onmouseclick unity

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;public class ExampleClass : MonoBehaviour
{
    void OnMouseDown()
    {
        // Destroy the gameObject after clicking on it
        Destroy(gameObject);
    }
}

Example 4: how to fix on Input.GetMouseButtonDown(0) conting as ui

using UnityEngine.EventSystems;

void Update()
{
	if (Input.GetMouseButtonDown(0))
    {
         // This line prevents the Code from activating UI
    	 if (EventSystem.current.IsPointerOverGameObject())
                return;
         // Put your code here       
    }
}

Tags:

Misc Example