Raycasting on a 2d game troubles

This is my biggest problem so far, still learning so bear with me. This is a broad type of question because I’m really pretty lost here, tried reading the documentation on raycasting and its helped a bit, but now I’ve really run into a problem.

ANYWAYS, so in my game I have a chest button and when you click it, a coin pops out etc. Now i’m not sure if raycasting is the best way to do this, but I’m trying to have it check if the object hit by the raycast is the chest, then it should have the coin pop out. The raycast is set to come from the mouse position and then check but I am running into multiple errors.

Here is what I’m working with

void Update()
	RaycastHit hit;
	Ray ray = new Ray(Camera.main.ScreenPointToRay(Input.mousePosition, Vector3.forward));

	if (hit.collider.tag == "Chest")  //not sure if the button has a collider and that may be an issue?
			//play coin animation


For the question if Raycast is the best way, it depends, if this button is a UI component than a raycast to it it’s already happening everytime you click. If that’s the case take a look at this tutorial:


First of all, when using raycast in a 2D enviroment you must declared your RaycastHit as a RaycastHit2D
and more importantly you forgot to accutualy cast the ray. hit = Physics2D.Raycast();, my guess is that you looked at the wrong raycast doc, take a look at this, it has a good exemple of what you trying to achieve.


And this is the documentation for raycast2D