Unity防止UI点击穿透

主要涉及API:

EventSystem.current.IsPointerOverGameObject()

EventSystem.current.IsPointerOverGameObject(Touch.fingerId)

//鼠标点击
if (EventSystem.current.IsPointerOverGameObject()) 
{
    //TODO:点击在了UI上
}

//手机上触屏模式需要传入手指ID
//经测试,始终返回false,未知原因
if (EventSystem.current.IsPointerOverGameObject(touch.fingerId)) 
{
    //TODO:点击在了UI上
}

同时再加上射线检测辅助判断

//放回值list.Count > 0 表示点击到了UI
bool CheckGuiRaycastObjects()
{
    PointerEventData eventData = new PointerEventData(es);
    eventData.pressPosition = Input.mousePosition;//touch.position
    eventData.position = Input.mousePosition;//touch.position

    var results= new List<RaycastResult>();
    curCanvas.GetComponent<GraphicRaycaster>().Raycast(eventData, results);
    //EventSystem.current.RaycastAll(eventData, results);   //使用此方式也可
    return list.Count > 0;
}

完整代码:

    void CheckClickUI()
    {
#if ((UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR)
            //Touch
            int touchCount = Input.touchCount;
            if (touchCount == 1)
            {            
                Touch t = Input.GetTouch(0);
                if(t.phase == TouchPhase.Began)
                {
                    //手机返回值异常,采用||
                    if (EventSystem.current.IsPointerOverGameObject (t.fingerId) || CheckGuiRaycastObjects(t.position))
                    {
                         //点击到UI
                    }
                }          
            }
 
#else
        //Mouse
        if (Input.GetMouseButton(0))
        {
            //PC返回值正常,双重判定
            if (EventSystem.current.IsPointerOverGameObject() && CheckGuiRaycastObjects(Input.mousePosition))
            {
                //点击到UI
            }
        }
#endif
    }
    
    bool CheckGuiRaycastObjects(Vector3 position)
    {
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.pressPosition = new Vector2(position.x, position.y);
        eventData.position = new Vector2(position.x, position.y);

        var results= new List<RaycastResult>();
        //curCanvas.GetComponent<GraphicRaycaster>().Raycast(eventData, results);//使用canvas进行检测也可
        EventSystem.current.RaycastAll(eventData, results);   
        return results.Count > 0;
    }

遇到的问题:

个人测试在手机上 EventSystem.current.IsPointerOverGameObject(Touch.GetTouch(0).fingerId) 始终返回的是false,不知是什么原因,希望有知道的朋友可以留言告知一下,再次感谢!

暂时做法是,手机上当EventSystem.current.IsPointerOverGameObject返回false时,再执行射线再次检测是否点击到UI

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值