Version: 2017.2

EventSystem.IsPointerOverGameObject

切换到手册
public bool IsPointerOverGameObject ();
public bool IsPointerOverGameObject (int pointerId);

参数

pointerId 指针(触控/鼠标)ID。

描述

具有给定 ID 的指针是否位于 EventSystem 对象上?

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

public class MouseExample : MonoBehaviour { void Update() { // Check if the left mouse button was clicked if (Input.GetMouseButtonDown(0)) { // Check if the mouse was clicked over a UI element if (EventSystem.current.IsPointerOverGameObject()) { Debug.Log("Clicked on the UI"); } } } }

如果使用没有参数的 IsPointerOverGameObject(),它将指向“鼠标左键”(pointerId = -1);因此,当您使用 IsPointerOverGameObject 进行触摸时,应该考虑将 pointerId 传递给该对象。

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

public class TouchExample : MonoBehaviour { void Update() { // Check if there is a touch if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { // Check if finger is over a UI element if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { Debug.Log("Touched the UI"); } } } }

请注意,对于触摸操作,应将 IsPointerOverGameObject 与“OnMouseDown()”、“Input.GetMouseButtonDown(0)”或“Input.GetTouch(0).phase == TouchPhase.Began”结合使用。