First, I know there are functions that automatically get called when a sprite is clicked, but I have to calculate everything from another script which sprite gets clicked.
Anyway, here’s the code:
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit hit;
if( Physics.Raycast( ray, out hit, 100 ) )
{
......................
Basically, it never makes it past that if. What am I doing wrong?
Sprites are 2D. Physics.Raycast() is 3D. You have to use some sort of 2D function to detect the hit on a 2D object. Note Sprites by default do not have a collider, so you will also need to add some sort of collider to your sprite. Then you can do something like:
var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit != null && hit.collider != null) {
Debug.Log("object clicked: "+hit.collider.tag);
}
An alternate approach (assuming an orthographic camera) would be to use Camera.ScreenToWorldPoint() and then test the position using Physics2D.OverlapPoint() or Physics2D.OverlapPointNonAlloc().