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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aiyan1111111/article/details/52815691

说明

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

点击到UI

这里我使判断的是Unity中所自带的UGUI 系统,判断是否点击到UI上:
UGUI系统提供的方法如下所示:
这里写图片描述
然后通过判断移动端、PC端作出相应的操作:
这里写图片描述

点击到3D物体

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

完整代码

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

/// <summary>
/// 全局Click检测
/// </summary>
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");
                }
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/aiyan1111111/article/details/52815691