Determine whether the UGUI interface is clicked (tool class)

Because there is often a need to click on the blank area to close the current page, I wrote a simple tool class that can add some custom events when the interface is closed. If you want to use it, just hang the script on whichever you want to close.

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

public class CloseSlefLogic : MonoBehaviour
{
    public UnityEvent closeHandle;

    private GameObject nowClick;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            nowClick = ClickObject();

            if (nowClick == null || (nowClick != gameObject && nowClick.transform.parent != transform))
            {
                closeHandle.Invoke();
            }
        }
    }

    public GameObject ClickObject()
    {
        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
        if (results.Count > 0)
        {
            return results[0].gameObject;
        }
        else
        {
            return null;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_33325776/article/details/122624962