Unity判断是否点击到UI、3D物体

说明

在移动端使用手指触碰情况下或者存在鼠标点击情况下,很多时候我们都需要对所点击到的东西做判断——是否点击在UI或者是否点击到3D物体上等,判断点击在UI上的时候是否同时点击到了3D物体上。。。

点击到UI

这里我使判断的是Unity中所自带的UGUI 系统,判断是否点击到UI上:
UGUI系统提供的方法如下所示:
Unity判断是否点击到UI、3D物体_第1张图片
然后通过判断移动端、PC端作出相应的操作:
Unity判断是否点击到UI、3D物体_第2张图片

点击到3D物体

这里我通过射线检测方式,判断是否点击到了3D物体,但这里存在一个缺陷,3D物体必须具有碰撞体:
Unity判断是否点击到UI、3D物体_第3张图片

完整代码

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

/// 
/// 全局Click检测
/// 
public class ClickEvent : MonoBehaviour
{

    private RaycastHit ObjHit;
    private Ray CustomRay;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
#if UNITY_ANDROID || UNITY_IPHONE
            //移动端判断如下
            if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
            //PC端判断如下
            if (EventSystem.current.IsPointerOverGameObject())
#endif
            {
                Debug.Log("当前点击在UI上" + EventSystem.current.currentSelectedGameObject);
            }
            else
            {
              //从摄像机发出一条射线,到点击的坐标
                CustomRay = Camera.main.ScreenPointToRay(Input.mousePosition);
                //显示一条射线,只有在scene视图中才能看到
                Debug.DrawLine(CustomRay.origin, ObjHit.point, Color.red, 2);
                if (Physics.Raycast(CustomRay, out ObjHit, 100))
                {
                    if (ObjHit.collider.gameObject != null)
                    {
                        Debug.Log("Click Object:" + ObjHit.collider.gameObject);
                    }
                }
                else
                {
                    Debug.Log("Click Null");
                }
            }
        }
    }

}

你可能感兴趣的:(Unity,Unity移动端技术开发)