Skip to content

Instantly share code, notes, and snippets.

@Cotoff
Created May 13, 2015 08:28
Show Gist options
  • Save Cotoff/8ecf105844eea0b1f175 to your computer and use it in GitHub Desktop.
Save Cotoff/8ecf105844eea0b1f175 to your computer and use it in GitHub Desktop.
A function to find Unity3D object at a given screen point, using 2D colliders
private Collider2D[] m_Hits=new Collider2D[16]; // 16 may not be enough for everyone.
private T GetTargetObject<T>(Vector3 mousePosition) where T:Component
{
var ray = Camera.main.ScreenPointToRay(mousePosition);
var pos = ray.GetPoint(-ray.origin.z/ray.direction.z);
var max = Physics2D.OverlapPointNonAlloc(pos, m_Hits);
for (int ii = 0; ii < max; ii++)
{
var hit = m_Hits[ii];
var res = hit.GetComponentInParent<T>();
if (res)
return res;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment