Stopping a raycast after hit

I noticed that my raycasts have been hitting multiple objects. Is there a way to stop a raycast after it hits an object? I’ve searched around but haven’t been able to find anything about it. I believe that Mathf.Infinity needs to be changed to something else.

jessee03, I think your question is very clear. I had exactly the same problem. I thought the raycast was shooting through two objects and, like you, I thought it had something to do with Mathf.Infinity.

You’ve probably solved it by now but here was what I was doing wrong:

	void Update() 
	{
		RaycastHit hitPoint;
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
		if(Physics.Raycast(ray, out hitPoint, Mathf.Infinity))
		{

			if(Physics.Raycast(ray, out hitPoint, Mathf.Infinity) == GameObject.FindGameObjectWithTag("Ground"))
			{
				Debug.Log("Hit ground"); 
			}
			
			if(Physics.Raycast(ray, out hitPoint, Mathf.Infinity) == GameObject.FindGameObjectWithTag("Object"))
			{
				Debug.Log("Hit object"); 
			}
		}
		else
		{
			Debug.Log ("No collider hit"); 
		}

	}

And this is what worked:

void Update() 
	{
		RaycastHit hitPoint;
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
		if(Physics.Raycast(ray, out hitPoint, Mathf.Infinity))
		{
			if(hitPoint.collider.tag == "Ground")
			{
				Debug.Log("Hit ground"); 
			}
		
			if(hitPoint.collider.tag == "Object")
			{
				Debug.Log("Hit object"); 
			}
		}
		else
		{
			Debug.Log ("No collider hit"); 
		}
	}

Spark is right; if you only want information on what the raycast first hits, then just use the first returned hit point.

If you mean drawing it, you could you use Debug.DrawLine from the raycast’s (Physics.Raycast) point of origin to the first hit point.

Hi. I know it’s kind of an old question, but here was my approach:

I did it with raycasting- I used RaycastAll and layers for my top down kind of moba style game, i used it for highlighting enemies and stuff. In Update you need :
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hits;
hits = Physics.RaycastAll(ray);

//then in the array of hits you check if the 0 element in the array is on the layer you are looking for,let’s //say shootable is on layer 9, and let’s assume ground is layer8
if (hits[0].collider.gameObject.layer==9)
{
hoveringShootable = hits[0].collider.gameObject;
hits[0].collider.gameObject.GetComponentInChildren().UserCall(true);
}

//It’s working for now, I hope it helps if you have the same obstacle I was facing!