Unity UI⭐️判断当前点击的是不是UI、获得当前点击的UI物体

2024-08-15 17:08:51 浏览数 (1)

 获取当前点击的是不是UI
代码语言:javascript复制
    void Update()
    {
        //场景中必须有EventSystem
        if (Input.GetMouseButtonDown(0))
        {
            if (EventSystem.current.IsPointerOverGameObject() || GUIUtility.hotControl != 0)
            {
              Debug.Log("单击到了UI");
            }
            else
            {
              Debug.Log("没有单击到UI");
            }
        }
    }

获得当前点击的UI物体

代码语言:javascript复制
    /// <summary>
    /// 获得当前点击到的UI物体
    /// </summary>
    public GameObject Skode_GetCurrentSelect()
    {
        GameObject obj=null;

        GraphicRaycaster[] graphicRaycasters = FindObjectsOfType<GraphicRaycaster>();

        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.pressPosition = Input.mousePosition;
        eventData.position = Input.mousePosition;
        List<RaycastResult> list = new List<RaycastResult>();

        foreach (var item in graphicRaycasters)
        {
            item.Raycast(eventData, list);
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i  )
                {
                    obj = list[i].gameObject;
                }
            }
        }

        return obj;
    }

大家还有什么问题,欢迎在下方留言

0 人点赞