1. 程式人生 > >unity API 之EventSystem.current.IsPointerOverGameObject()

unity API 之EventSystem.current.IsPointerOverGameObject()

inpu example point ecs nbsp systems upd 檢測 down

命名空間 :UnityEngine.EventSystems

官方描述:

public bool IsPointerOverGameObject(); public bool IsPointerOverGameObject(int pointerId); //觸摸屏時需要的參數,即檢測觸碰的手值 Is the pointer with the given ID over an EventSystem object? 代碼:
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()) //檢測是否點擊了UI上的物件,返會bool值 { Debug.Log("Clicked on the UI"); } } } }

當使用觸屏時,官方給出了另外一份代碼

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)) //監視是否觸碰UI { Debug.Log("Touched the UI"); } } } }
總結:可以用此API避免在畫面中點擊到UI的物件又同時點到Game中的物件觸發的一些情況;在觸屏中可以判斷點擊的手指並執行相應的函數事件。


unity API 之EventSystem.current.IsPointerOverGameObject()