Detecting mouse clicks outside of UI elements

I am attempting to create a context menu when I click on monobehaviors inside the UI

The behavior I want is for when I right click on a monobehavior, it will open the context menu. Then when I click on something inside the context menu, it will not close the context menu, but when I click outside the context menu, it will close the menu.

I was having trouble with IPointerHandler, and I eventually decided to start checking the mouse position on the screen and simply closing the context menu if there is a click detected and its outside the context menu

My question is, does anyone know a simpler solution to this problem?

public class ContextMenu : MonoBehaviour
    {
        private Vector3[] corners = new Vector3[4];
        private RectTransform rectTransform;
        
        private void Awake()
        {
            rectTransform = GetComponent<RectTransform>();
        }

        public void Update()
        {
            if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1))
            {
                rectTransform.GetWorldCorners(corners);
                
                if (corners[0].x > Input.mousePosition.x || corners[2].x < Input.mousePosition.x ||
                    corners[0].y > Input.mousePosition.y || corners[2].y < Input.mousePosition.y)
                {
                    Constants.OpenContextMenu(false);
                }
            }
        }
    }

bool mouseInside = RectTransformUtility.RectangleContainsScreenPoint(rectTransform, mousePosition);

1 Like