Skip to content

Instantly share code, notes, and snippets.

@attilam
Created November 14, 2012 14:31
Show Gist options
  • Save attilam/4072422 to your computer and use it in GitHub Desktop.
Save attilam/4072422 to your computer and use it in GitHub Desktop.
Raycast for the closest object with a specific tag in Unity
public static bool RaycastWithTag(Ray ray, out RaycastHit hit, float distance, string tag, int layerMask = System.Int32.MaxValue) {
RaycastHit[] hits = Physics.RaycastAll(ray, distance, layerMask);
hit = new RaycastHit();
hit.distance = distance;
foreach(RaycastHit ahit in hits) {
if ( ahit.distance < hit.distance && ahit.transform.CompareTag(tag) ) {
hit = ahit;
}
}
if (hit.distance < distance)
return true;
else
return false;
}
@LaikWQC
Copy link

LaikWQC commented Apr 27, 2022

public static bool RaycastWithTag(Ray ray, out RaycastHit? hit, float distance, string tag, int layerMask = System.Int32.MaxValue) 
{
	RaycastHit[] hits = Physics.RaycastAll(ray, distance, layerMask).Where(x => x.transform.CompareTag(tag)).ToArray();
	switch(hits .Length)
        {
            case 0:
                hit = null;
                return false;
            case 1:
                hit = hits [0];
                return true;
            default:
                hit = tiles.OrderBy(x => x.distance).First();
                return true;
        }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment