Touch Detection in 2D Game

Using following code I can able to detect touch of 3d box collider but when I attach Box Collider 2D, the code does not work.

    RaycastHit hit;
    
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    
    if (Physics.Raycast(ray, out hit))
    {}

So how to detect touch for Box Collider 2D?

For 2D and an Orthographic camera, you can do it like this:

void Update () {
	Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
	RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
	if (hit != null && hit.collider != null) {
		Debug.Log ("I'm hitting "+hit.collider.name);
	}
}

There is another line or two if you are using a Perspective camera.

why not use this instead?

JavaScipt

function OnMouseOver () {
   if(Input.GetMouseButtonDown(0)){
   //your code
   }
}

Ok, I recently had to implement this very same functionality. I had code for 3D colliders and didn’t want to change it too much.
So in 3D I was doing this:

var ray = Camera.main.ViewportPointToRay(new Vector3(touch.Position.x, touch.Position.y, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit)){
    //Do stuff
}

The equivalent in 2D is:

var ray = Camera.main.ViewportPointToRay(new Vector3(touch.Position.x, touch.Position.y, 0));
var hit = Physics2D.GetRayIntersection(ray);
if (hit.collider != null) {
    //Do stuff
}