I have 3D world. I want to detect when the player clicks on a game object in the world.
In this image, I have 2 objects I want to detect mouse click on. The white sphere does have collider on it. The dumpster does not. The behavior is the same as noted below.
I am getting the mouse down detection. When I check the RaycastHit
, I always get the player game object transform and not the game object I clicked on in the world. If I remove the raycaster checks, then I get mousedown for anything in the game not just mouse down over the game object. I need to be able to distinguish between clicks on different game objects.
I found a post here and added a PhysicsRayCaster, but it didn't change the behavior. The problem isn't getting the event. My problem is detecting which game object the player clicked on in the world.
Here's my code:
public class InventoryItemSearchHandler : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// CompareTo always fails because hit.transform.name is always "Player" and
// not the name of the object clicked on
if (0 == hit.transform.name.CompareTo(transform.name))
{
print("mouse down");
}
}
}
}
}
EDIT: In the image below (compared to the one above) I do get the correct transform in the RaycastHit type when I click on the white sphere (and when I click on the dumpster I get the player transform as noted above).
So it looks like the player object is getting in the way. What would be causing that?