unity detect click on gameobject 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 check when clicked on object

void Update()
{
  // Check for mouse input
  if (Input.GetMouseButton(0))
  {
  	Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   	RaycastHit hit;
   	// Casts the ray and get the first game object hit
   	Physics.Raycast(ray, out hit);
   	Debug.Log("This hit at " + hit.point );
  }
}

Example 3: unity if gameobject is clicked

void OnMouseDown() 
 {
   Debug.Log("Mouse is down")
 } 

 void OnMouseUp() 
 {
   Debug.Log("Mouse is up")
 } 

 void OnMouseClick() 
 {
   Debug.Log("Mouse is clicked (down then up its 1 click)")
 } 

// Works only if the gameobject have a collider

Example 4: detect object click unity

void Update () {      }  void OnMouseDown(){         // this object was clicked - do something     Destroy (this.gameObject);  }

Example 5: how to click a gameobject in unity

using UnityEngine.UI;

public Text text;
text.text = "new text";