using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ShieldUIOver
{
public static ShieldUIOver Instance = new ShieldUIOver();
public ShieldUIOver()
{ }
/// <summary>
/// 传入手指ID
/// </summary>
/// <param name="fingerID"></param>
/// <returns></returns>
public bool IsPointerOverUIObject(int fingerID)
{
return EventSystem.current.IsPointerOverGameObject(fingerID);
}
/// <summary>
///相机有Physics Raycaster组件 通过EventSystem 可以检测到UI,3D物体
///没有Physics Raycaster组件 通过EventSystem 只可以检测到UI
/// 如果Physics Raycaster组件 可以考虑选择是否要过滤3D物体
/// </summary>
/// <param name="screenPosition"></param>
/// <returns></returns>
public bool IsPointerOverUIObject(Vector2 screenPosition)
{
//实例化点击事件
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
//将点击位置的屏幕坐标赋值给点击事件
eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y);
List<RaycastResult> results = new List<RaycastResult>();
//向点击处发射射线
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
//TODO: 下面是检测到UI后屏蔽向下传递的事件,只检测UI
//for (int i=results.Count-1;i>=0; i-- )
//{
// Debug.LogError(results[i].gameObject.name);
// if (results[i].gameObject.layer==LayerMask.NameToLayer("Default"))
// {
// results.RemoveAt(i);
// }
//}
//Debug.Log(results.Count);
return results.Count > 0;
}
/// <summary>
/// 通过画布上的 GraphicRaycaster 组件发射射线
/// 只会检测到UI,不会检测到3D物体
/// </summary>
/// <param name="canvas"></param>
/// <param name="screenPosition"></param>
/// <returns></returns>
public bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition)
{
//实例化点击事件
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
//将点击位置的屏幕坐标赋值给点击事件
eventDataCurrentPosition.position = screenPosition;
//获取画布上的 GraphicRaycaster 组件
GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
List<RaycastResult> results = new List<RaycastResult>();
// GraphicRaycaster 发射射线
uiRaycaster.Raycast(eventDataCurrentPosition, results);
return results.Count > 0;
}
}
测试脚本
public class TestEvent : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//EventSystem 传递坐标
if (ShieldUIOver.Instance.IsPointerOverUIObject(Input.mousePosition))
{
Debug.Log("方法二: 点击在UI 上");
}
//画布组件,传递坐标
if (ShieldUIOver.Instance.IsPointerOverUIObject(GetComponent<Canvas>(), Input.mousePosition))
{
Debug.Log("方法三: 点击在UI 上");
}
}