Created
May 13, 2015 08:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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