How to get object clicked by mouse but not when it is behind the button that was clickecked?

Viewed 328

I use this code to get an object clicked by the mouse

void Update() {
  if (Input.GetMouseButtonUp(0)) {
    RaycastHit hit;
    Ray ray = camera.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit)) {
      Transform objectHit = hit.transform;
    }
  }
}

This code works even when I click the button and do not want to click an object that is behind the button. How to avoid it?

3 Answers

There is simple solution in Unity. You need to use this function, it returns true if mouse pointer is over UI element, like button.

EventSystem.current.IsPointerOverGameObject()

Like this:

void Update()
{
    if (Input.GetMouseButtonUp(0) && !EventSystem.current.IsPointerOverGameObject())
    {
        // UI wasn't clicked
        ...
    }
}

You could instead implement the IPointerDownHandler and IPointerUpHandler interfaces on the target object you want to click on like

public class Interactable3D : MonoBehaviour, IPointerUpHandler
{
    public void OnPointerDown(PointerEventData pointerEventData)
    {
        Debug.Log(name + "Game Object Click in Progress");
    }

    public void OnPointerUp(PointerEventData pointerEventData)
    {
        // Whatever should happen
    }
}

Use the IPointerUpHandler Interface to handle pointer up input using OnPointerUp callbacks. Ensure an EventSystem exists in the Scene to allow click detection. For click detection on non-UI GameObjects, ensure a PhysicsRaycaster is attached to the Camera.

And ofcourse it still requires to have a Collider attached.

You can use a Layer Mask, you can assign the gameobject that you don't want to click to the ignore raycast layer.

you can read more about that here : Unity Documentation - LayerMask

Related