How to detect click events on overlapping UI elements?
I am trying to detect a click event on a UI Image that is behind another UI image. Both images need to be able to be clicked at the same time, so effectively one mouse click triggers the OnPointerClick event in a script that is attached to both UI objects, however the object on top always blocks the one below.
I have created an example Unity scene (attached) to hopefully illustrate the issue a bit more. In my example I have a red square and a blue square that intersect in the middle. Clicking on any part of the screen where the images do not intersect triggers the correct single click event as expected, but clicking the purple part in the middle only selects the blue square (as it is on top). Is there a way clicking on the purple part can trigger both click events?
It seems like there should be a simple solution, but I haven't had any luck finding it.
Answer by Vector3Games · May 15, 2018 at 11:07 AM
So it doesn't seem like there is a simple solution as I'd hoped, but for the benefit of anyone who comes across this question in the future I have solved my problem by creating a script that uses Graphic Raycasting to manually invoke buttons/functions. See:
https://docs.unity3d.com/ScriptReference/UI.GraphicRaycaster.Raycast.html
Example script (Attached to Canvas):
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
public class UIOverlappingFix : MonoBehaviour
{
private GraphicRaycaster raycaster;
private PointerEventData pointerEventData;
private EventSystem eventSystem;
void Start()
{
raycaster = GetComponent<GraphicRaycaster>();
eventSystem = GetComponent<EventSystem>();
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Mouse0))
{
pointerEventData = new PointerEventData(eventSystem);
pointerEventData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
raycaster.Raycast(pointerEventData, results);
bool firstTargetIgnored = false;
foreach (RaycastResult result in results)
{
// Ignore the first target with raycastTarget as this will receive the normal click event trigger
// This prevents the first raycastTarget being invoked twice
if (firstTargetIgnored)
{
if (result.gameObject.GetComponent<Button>())
{
Debug.Log("INVOKED:" + result.gameObject.name);
result.gameObject.GetComponent<Button>().onClick.Invoke();
}
}
if ( ! firstTargetIgnored)
{
firstTargetIgnored = true;
}
}
}
}
}