How do you make an object respond to a click in C#

There are two main alternatives:

1- Use OnMouseDown in the object script. This is the best alternative when you want only some objects to respond to clicks - only the ones that have OnMouseDown in their scripts will sense the click:

void OnMouseDown(){
  // this object was clicked - do something
}

2- Use Physics.Raycast to find which object is being clicked - this is better when you want to click any object in scene, since a single script attached to the camera does the job:

void Update(){
  if (Input.GetMouseButtonDown(0)){ // if left button pressed...
    Ray ray = camera.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit)){
      // the object identified by hit.transform was clicked
      // do whatever you want
    }
  }
}

NOTE: Only scene objects that have a collider can be clicked, with exception of GUITexture and GUIText, which respond to OnMouse events (but not to Raycast)

place void OnMouseDown () { …} outside of the update method like this:

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

For Single object is ok , i have 5 cubes

i need only one script but i will use different functions for the these objects

how do i have to write the code for this in one script

Just in case if you have a 2D project and the previous script doesn’t work for you - use this:

void Update ()
{
if (Input.GetMouseButtonDown(0))
        {
            Vector3 clickpos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            Vector2 click2D= new Vector2(mousePos.x, mousePos.y);

            RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
            if (hit.collider != null)
            {
                Debug.Log(hit.collider.gameObject.name);
            }
        }
}

@krotovar
im little bit confused :slight_smile:
origin = current mouse Pos , direction = Vector2.zero so this code should collide eveything on the way(red line) but only hit if i click directly object how is possible. And distance is 0 how is drawing a ray. Btw i also try Debug.DrawRay doesnt help or i couldnt use corretly. You can see codes below.

I drew how am i thought.