Raycast on a 2D Collider

I want to raycast from the camera to the mouse location for my @D Game to identify which Object was clicked.

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

    RaycastHit hit;
    if(Physics.Raycast(ray,out hit))
    {
        isHit = false;
        Destroy(GameObject.Find(hit.collider.gameObject.name));

    }

Raycasting on 2D Colliders doesn’t seem to work.

For 2D Colliders you need use Physics2D and RaycastHit2D instead of Physics.

void Update(){
		
		RaycastHit2D hit = Physics2D.Raycast(cameraPosition, mousePosition, distance (optional));
		
		if(hit != null && hit.collider != null){
			isHit = false;
        	Destroy(GameObject.Find(hit.collider.gameObject.name));
		}
	}

Use it with a Vector2 mousePosition or if your game is 3D use 3D colliders instead of 2D.

Use the following to cast 3D rays against 2D colliders:

Physics2D.GetRayIntersection(...)
Physics2D.GetRayIntersectionAll(...)

You can try this solution given in this 1

If you’re using the new 2d stuff you’ll need to use the Physics2D functions.

As you have found, 3D Raycasting (Physics.Raycast()) on a 2D colliders does not work. You have a couple of choices. First Monobehaviour.OnMouse* functions do work, so you can put a script directly on the object. If you want to Raycast(), then an alternate solution is to put a 3D collider on an empty child game object and size the collider as appropriate to your sprite. You can use the Transform.parent to access the sprite.

private void OnClickGUIWidget(Vector3 position)
{

	Ray ray = Camera.main.ScreenPointToRay(position);
	RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);

	if (hit != null) 
	{
		if (hit.collider !=null)
		{
			Button _btn = hit.transform.gameObject.GetComponent<Button> ();
			
			if (_btn != null )
			{
				if (_btn.name == GlobalVar.button_name_exit)
				{
					Application.Quit();
				}
				
				if (_btn.name == GlobalVar.button_name_restart)
				{
					Application.LoadLevel(0);
				}
			}
		}
	}
}

If anyone else comes across an issue like this and like me couldn’t get anything to work, what I did was basically what @MarcosLC suggested with using 3d colliders. None of the other suggestions here or anywhere else worked, not even the obvious routes like using the Physics2D options, Physics2D.GetRayIntersection, or eventsystem.current.etcetc…


I needed to check both a 3D object and a button element at the same time, and no matter what I tried nothing worked, except this:

Used 3D box colliders for button elements instead of 2D, and in the Canvas set the Render Mode to Screen Space - Camera and set the plane distance to 1. It’s not perfect, but at least it allowed me to keep everything in the same space and reduce complexity, and you know, actually work. So after all these years, thank you, @MarcosLC.