How do i change this script so it works with 2D colliders?

The following script only works with 3D colliders and it doesnt print “hit” at all with 2D colliders, can someone help change it to work with 2D colliders instead.

    if (Input.GetMouseButtonDown(0))
     {
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     RaycastHit hit;
     
     if (Physics.Raycast(ray, out hit) && this.gameObject.Equals(hit.transform.gameObject)) Debug.Log ("Hit");
     else Debug.Log ("Miss");
     }

if (Input.GetMouseButtonDown(0))
{
Ray2D ray2D = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit2D;

			if (Physics2D.Raycast(ray2D, out hit2D) && this.gameObject.Equals(hit2D.transform.gameObject)) Debug.Log ("Hit");
			else Debug.Log ("Miss");
		}

If you want to check for both collider 2D and 3D you need to do raycast for two times.

There is a small difference between Physics.Raycast and Physics2D.Raycast, please look at the scripting API before asking questions like this.

Physics for 3D:

Physics for 2D:

Physics.Raycast returns a bool, and uses “out hit” to give you information about the hit. Physics2D.raycast returns a object of type “Raycast2DHit” which holds information about the hit.

You can do like this:

RaycastHit2D hit = Physics2D.Raycast(rayOrigin, rayDirection, rayLength, collisionMask);

and then you can access information about whats been hit like this:

if (hit)
    {
      hit.*whatever*
    }

With 2D colliders, you need to use Physics2D, not Physics. However, this means you won’t be able to use a raycast because Physics2D only allows raycasts in the 2D plane. You probably want to do something like this:

var point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var hit = Physics2D.OverlapPoint(point);