[Solved] Allow overlapping buttons in Unity UI to all process the click event.

I have 2 buttons that overlap a bit. I want that if the overlapping area is clicked, both buttons get triggered. I have no idea where to start.

You could create a hidden third button that just covers the part where they overlap so that it could trigger both buttons when it’s pushed.

That wouldn’t work in my case. I did just find a very flexible way to do this:

using System.Collections.Generic;
using UnityEngine.EventSystems;

namespace MyUI
{
    public sealed class EventBubbler : MonoBehaviour, IPointerClickHandler, IPointerUpHandler, IPointerDownHandler
    {
        private void Bubble<T>(PointerEventData eventData, ExecuteEvents.EventFunction<T> eventFunction) where T : IEventSystemHandler
        {
            var allRaycasted = new List<RaycastResult>();
            EventSystem.current.RaycastAll(eventData, allRaycasted);
            foreach (var raycasted in allRaycasted)
            {
                if (raycasted.gameObject == gameObject)
                {
                    continue;
                }
                ExecuteEvents.Execute(raycasted.gameObject, eventData, eventFunction);
            }
        }

        void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
        {
            Bubble(eventData, ExecuteEvents.pointerClickHandler);
        }

        void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
        {
            Bubble(eventData, ExecuteEvents.pointerDownHandler);
        }

        void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
        {
            Bubble(eventData, ExecuteEvents.pointerUpHandler);
        }
    }
}

Just place it on the GO you want to allow to bubble events.

2 Likes

@
I was looking for ways to make this possible for several hours…
that script very helpful for me, thanks!