Unity检测点击到UI上

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

/// <summary>
/// 输入控制,判断当前点击是否在UGUI上面.
/// </summary>
public class InputUtility {

	public static bool IsOnUI = false;//手动控制

	private static List<RaycastResult> m_list = new List<RaycastResult>();

	/// <summary>
	/// 判断鼠标是否在UGUI上面
	/// </summary>
	/// <returns>如果在UGUI上,返回true.</returns>
	public static bool CheckMouseOnUI() {
		if (IsOnUI) return true;
		return IsPointerOverGameObject();
	}


	/// <summary>
	/// 判断是否在ugui上面
	/// </summary>
	/// <returns><c>true</c>, if mouse on UGU was checked, <c>false</c> otherwise.</returns>
	static bool IsPointerOverGameObject() {
		if (EventSystem.current) {
			if (Input.touchCount > 0) {
				for (int i = 0; i < Input.touchCount; ++i) {
					if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(i).fingerId)) {
						return true;
					}
				}
			}
			else {
				return EventSystem.current.IsPointerOverGameObject();
			}
			PointerEventData eventData = new PointerEventData(EventSystem.current);
			eventData.pressPosition = Input.mousePosition;
			eventData.position = Input.mousePosition;

			m_list.Clear();
			EventSystem.current.RaycastAll(eventData, m_list);
			return m_list.Count > 0;
		}
		return false;
	}

	public static bool IsPointerOverGameObject(Canvas canvas, Vector2 screenPosition) {
		if (IsOnUI) return true;

		if (EventSystem.current == null) return false;

		PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
		eventDataCurrentPosition.position = screenPosition;
		UnityEngine.UI.GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<UnityEngine.UI.GraphicRaycaster>();

		m_list.Clear();
		uiRaycaster.Raycast(eventDataCurrentPosition, m_list);

		return m_list.Count > 0;
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值