How to detect an instance of a gameobject using raycast2D

Hello,

So I’m making a top down 2D game and I am using Phsyics2D.Raycast in order to detect whether or not I’m hitting something.

What I want to do is detect the instance of the gameObject I hit and use SendMessage to call the function to take health off of that instance.

The problem is I’m not sure how I can “find” the instance of the gameObject the raycast hit rather than finding every gameObject with a specific name. In other words if there’s 10 enemies on the screen, I just want to take health off of the enemy I hit, not every enemy (since enemies are going to be made using prefabs).

Here is the code I have so far:

	public bool foundHit;	
	RaycastHit2D meleehit;

void meleeAttack()
	{
		if(Input.GetMouseButtonDown (0)) {

			foundHit = Physics2D.Raycast(transform.position, direction, dist);
			meleehit = Physics2D.Raycast(transform.position, direction, dist);
			Debug.DrawRay(transform.position, direction, Color.green);

			if(foundHit){
				meleehit.collider.gameObject.SendMessage ("takeDamage");
			}
		}
	}

I’m not entirely sure how RaycastHit2D works but I was guessing it has something to do with that, which is why I tried to put that in. The (“takeDamage”) just refers to the function on the health script of the enemy that takes away damage. As of right now it just takes away my own damage whenever I click.

Any help is appreciated!

yeah I was testing whether using a RaycastHit2D would make any difference, which is why there’s two.

I didn’t think about it hitting its own collider, but I’m going to make something along the line of if it hits and its tagged as enemy then take off health from that gameobject instance