Raycast not hitting anything.

Here’s my scenario. There’s a background sprite set on background layer and multiple player sprites set on player layer. The idea is to be able to select any player unit by moving the mouse over it and left clicking it. This would allow you to move it whenever you want. Problem is, I need to detect what I just clicked on.

And that’s there the problem comes out. Through some googling, I find out I will need to use raycasting. However, even if my player unit objects have box colliders, the raycast ignores literally everything.

void Update () 
	{
		Ray ray = GetComponent<Camera>().ScreenPointToRay (Input.mousePosition);
		RaycastHit hit;
		if (Physics.Raycast (ray, out hit)) 
		{
			Debug.Log ("This hit at " + hit.collider.name);
		} 
	}
}

This script snippet is in my camera object. I know it’s not supposed updating, but it’s simply to see if it hits ANYTHING ever. It doesn’t. While I can select and move the units already, that method is really hacky and clunky, and this could allow me to do the sensible thing of not letting one unit to be placed on top of another, or allowing me to deselect the current unit if another is clicked, etc.

You said sprites, which makes me think this is a 2D game. Are you sure that your objects have box colliders, and not Box Collider 2Ds?

Raycast is part of the PhysX 3D physics engine, which requires objects to have 3D colliders (box, sphere, capsule etc.)

If your objects have 2D colliders (polygon, box collider 2D etc.) then you’re going to want to use Physics2D.Raycast instead.

u can attach a script to each unit containing the OnMouseDown() function which will get invoked each time the object is pressed and then deal with the selected unity though some sort of manager