Skip to content

Instantly share code, notes, and snippets.

@nastajus
Created April 26, 2015 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nastajus/18a38220258eefdfd0b2 to your computer and use it in GitHub Desktop.
Save nastajus/18a38220258eefdfd0b2 to your computer and use it in GitHub Desktop.
Casts (and shows) a ray detecting all objects and their multiple components from the mouse cursor position outward from the camera position in the camera's direction. Always works in only Scene pane, but Gizmos needs to be on and the direction away from camera changed to see in Game pane.
// Update is called once per frame
private void Update()
{
ShowHitsComps();
}
/**
Casts (and shows) a ray detecting all objects and their multiple components from the mouse cursor
position outward from the camera position in the camera's direction. Always works in only Scene
pane, but Gizmos needs to be on and the direction away from camera changed to see in Game pane.
*/
void ShowHitsComps()
{
Vector3 origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = Camera.main.transform.forward; //or just Vector3.forward;
Debug.DrawRay(origin, direction * 20f);
List<RaycastHit2D> hits = Physics2D.RaycastAll(origin, direction).ToList();
if (hits.Count > 0)
{
foreach (RaycastHit2D hit in hits)
{
foreach (var component in hit.transform.gameObject.GetComponents<Component>())
{
Debug.Log(hits.Count + ", " + hit.transform.gameObject.name + ", " + component.ToString());
}
}
Debug.Log("================");
}
else
{
Debug.Log(hits.Count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment