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
先搭建一个简单的场景,如下:
Unity3dUGUI鼠标穿透UI问题的解决方法_第1张图片
完成结果
下面就是我们的解决方法了:

完整版

    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;
/// 
/// 脚本位于Canvas画布上
/// 
public class PointerPenetrate : MonoBehaviour
{
    /// 
    /// cube
    /// 
    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().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");
            }
        }

    }
}

记得观察控制台的输出喔


Unity3dUGUI鼠标穿透UI问题的解决方法_第2张图片
现在就可以尽情的点击测试了

你可能感兴趣的:(Unity3dUGUI鼠标穿透UI问题的解决方法)