Click outside of UI element

Anyone here have an idea what the best way is, to find out when there was a click outside the given element? For example to close a modal.

One way of implementing this is to add an invisible layer and place it at lowest layer depth. Whenever you detect a click on that layer, have all modal closed.

This solution could be made more efficient if you also call the close method whenever you clicked something except the modal itself.

Good luck. Btw, it would be awesome if you could blog the solution after implemented it :slight_smile:

Hey louisgv,

yeah, I figured that that’s the bare bones solution, but I was hoping for something more efficient. FYI, I added an empty Text component to my canvas, which makes it clickable. Then I have a script that triggers an event that my view itself can subscribe to.

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

public class CanvasClick : MonoBehaviour, IPointerClickHandler {
   
    public event System.Action onCanvasClicked;

    public void OnPointerClick(PointerEventData eventData) {
        if (onCanvasClicked != null)
            onCanvasClicked();
    }
}
1 Like