Unity3dUGUI鼠标穿透UI问题的解决方法

当我们使用UGUI的时候会经常遇到鼠标穿透的问题,就是说在UGUI和3D场景混合的情况下,点击UI区域同时也会 触发3D中物体的鼠标事件。比如下图中:

UGUI鼠标穿透问题解决

那么这时候我们就需要解决这个棘手的问题了,其实也不难,只需要检测鼠标是否点击在UI元素上就可以了,zero利用的是EventSystem(事件系统);
当然了,或许有些朋友不懂EventSystem.current.IsPointerOverGameObject()是什么,没关系,zero已经为你附上了unity官网的链接地址:
http://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
先搭建一个简单的场景,如下:

完成结果

下面就是我们的解决方法了:

 

完整版

    void Update()
    {
#if (UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR
        if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
            {

            }
        }
#else
        if (Input.GetMouseButtonUp(0))
        {
            if (!EventSystem.current.IsPointerOverGameObject())
            {

            }
        }
#endif

    }

using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 脚本位于Canvas画布上
/// </summary>
public class PointerPenetrate : MonoBehaviour
{
    /// <summary>
    /// cube
    /// </summary>
    public GameObject cube;

    void Update()
    {
        //按下鼠标左键
        if (Input.GetMouseButtonDown(0))
        {
            //当前检测到的是否是UI层   
            if (EventSystem.current.IsPointerOverGameObject())
            {
                //是UI的时候,执行相关的UI操作
                Debug.Log("是UI");
            }
            else
            {
                //不是UI层的时候,执行其它操作
                Debug.Log("不是UI");

                //射线检测
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

                //定义射线检测器
                RaycastHit hitInfo;

                if (Physics.Raycast(ray, out hitInfo))
                {
                    //如果当前射线检测到的对象的名字是cube
                    if (hitInfo.collider.name == "Cube")
                    {
                        //改变cube的颜色,随机一个颜色
                        cube.GetComponent<MeshRenderer>().material.color =
                            new Color(Random.value, Random.value, Random.value, 1.0f);
                    }
                }
            }
        }
       //【更新内容】安卓上判断是否点击在UI还是3D物体
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)

        {
            if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))

            {
                Debug.Log("Hit UI, Ignore Touch");
            }

            else

            {
                Debug.Log("Handle Touch");
            }
        }

    }
}

记得观察控制台的输出喔

 

现在就可以尽情的点击测试了



作者:好怕怕
链接:https://www.jianshu.com/p/03dc654dfadc
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值