How to block mouse click when scene has graphics raycaster and physics raycaster

In my code I want to know when the mouse is down, so I can see if the mouse drags on the screen to rotate the camera, but I want this dragging to only occur while not on any UI component.

At first I tried to read EventSystem.current.IsPointerOverGameObject(). The problem with this was that I was using a graphics raycaster on my UI canvas but also a physics raycaster on my camera so that I can click on 3D objects as well. My UI is blocking click through just fine, but IsPointerOverGameObject would always return true because both raycasters would hit colliders.

Next I tried getting all objects hit by a raycast from the EventSystem to see if any of them were a UI object—by testing to see if their transform is a RectTransform. Code appropriated from here:

PointerEventData cursor = new PointerEventData(EventSystem.current);
// This section prepares a list for all objects hit with the raycast
cursor.position = Input.mousePosition;
List<RaycastResult> objectsHit = new List<RaycastResult>();
EventSystem.current.RaycastAll(cursor, objectsHit);
foreach(RaycastResult rr in objectsHit) {
	if (currentRaycast.gameObject.transform is RectTransform) return;
}

This did the trick, but then I wanted to make the code more efficient. This post tells about getting the latest raycast from the input module. So a new raycast isn’t needed, and this returns only the object that was the focus of the click:

Custom input module that exposes the latest PointerEventData:

public class CustomStandaloneInputModule : StandaloneInputModule
{
	public PointerEventData GetPointerData()
	{
		return m_PointerData[kMouseLeftId];
	}
}

And the updated code:

RaycastResult currentRaycast =
  ((CustomStandaloneInputModule)EventSystem.current.currentInputModule)
	.GetPointerData().pointerCurrentRaycast;
if (currentRaycast.gameObject.transform is RectTransform) return;

Works great for me. Hope this helps someone.

The post is the answer :slight_smile: