Check if clicked on UI or GameObject

Hey,
I’m facing this problem from a few days, couldn’t find any solution. I’m having a panable scene. While panning sometimes objects with collider come under some UI button. Now if I click on that UI button both collider and button are clicked, but I want only button to be clicked in this case. My head is hurting solving this problem.

I tried using EventSystem.current.IsPointerOverGameObject() but didn’t helped much
Any help here would really be great.

I am not an expert, but I guess you could try something with layers… If you prioritize an layer you got your UI on I guess that would work

@manipalsingh

  1. Put a Physics RayCaster on your main camera.

  2. Change the code in scripts on your world objects that handles mouse interaction from the old OnMouseDown, OnMouseUp callbacks etc. to the new call-backs by implementing the newer pointer interfaces.

For example to replace OnMouseUpAsButton() in your script:

First make your script implement the interface UnityEngine.EventSystems.IPointerClickHandler

Then change your method which might look like this:

public void OnMouseUpAsButton()
{
   // Your code
}

to

void IPointerClickHandler.OnPointerClick(EventSystems.PointerEventData eventData)
{
   // Your code
}

Now your objects are using the same system to handle raycasts for clicks and your clicks will not pass through the UI anymore.

What you can do is this:

GraphicRaycaster raycaster;
PointerEventData pointerEventData;
EventSystem eventSystem;
bool isInteractingWithUI = false;

private void Start()
    {
        raycaster = FindObjectOfType<GraphicRaycaster>();
        eventSystem = FindObjectOfType<EventSystem>();
    }

private void Update()
    {
        pointerEventData = new PointerEventData(eventSystem);
        //Set the Pointer Event Position to that of the mouse position
        pointerEventData.position = Input.mousePosition;

        //Create a list of Raycast Results
        List<RaycastResult> results = new List<RaycastResult>();

        //Raycast using the Graphics Raycaster and mouse click position
        raycaster.Raycast(pointerEventData, results);

        isInteractingWithUI = results.Count > 0;
        
        // foreach (RaycastResult result in results)
    }

public bool GetIsInteractingWithUI()
    {
        return isInteractingWithUI;
    }

Hope this helps someone!