转载自:雨松MOMO 2014年10月27日 于 雨松MOMO程序研究院 发表
http://www.xuanyusong.com/archives/3327
UI和3D场景同时都需要响应触摸事件,如果同时响应可能就会出现触摸UI的时候影响到了3D部分。为了解决这个问题在判断3D响应之前要先判断手指是否点击在UI上:
UGUI 提供了一个检测是否点击在UI上的方法 :EventSystem.current.IsPointerOverGameObject();
#if UNITY_ANDROID && !UNITY_EDITOR #define ANDROID #endif #if UNITY_IPHONE && !UNITY_EDITOR #define IPHONE #endif using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.EventSystems; public class NewBehaviourScript : MonoBehaviour { // Use this for initialization void Start () { } void Update() { if (Input.GetMouseButtonDown(0)||(Input.touchCount >0 && Input.GetTouch(0).phase == TouchPhase.Began)) { #if IPHONE || ANDROID if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) #else if (EventSystem.current.IsPointerOverGameObject()) #endif Debug.Log("当前触摸在UI上"); else Debug.Log("当前没有触摸在UI上"); } } }
IsPointerOverGameObject():
public bool IsPointerOverGameObject();
Parameters/参数
pointerId
Pointer (touch / mouse) ID.
Description/描述
Is the pointer with the given ID over an EventSystem object?/所给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"); } } } }
If you use IsPointerOverGameObject() without a parameter, it points to the "left mouse button" (pointerId = -1); therefore when you use IsPointerOverGameObject for touch, you should consider passing a pointerId to it.
/如果你使用不带参数的IsPointerOverGameObject()方法,默认指鼠标左键;因此当你想在触摸屏中使用IsPointerOverGameObject()方法,你应该为它顺便指定个参数。
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"); } } } }
Note that for touch, IsPointerOverGameObject should be used with OnMouseDown() or Input.GetMouseButtonDown(0) or Input.GetTouch(0).phase == TouchPhase.Began.
#if IPHONE || ANDROID
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
if (EventSystem.current.IsPointerOverGameObject())
#endif
。。。。。。
——这里#if #else #endif,功能叫平台依赖编译(Platform Dependent Compilation),判断当前所在平台,从而调用相应code;
官方API:https://docs.unity3d.com/Manual/PlatformDependentCompilation.html