官方文档:https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.html
EventSystem
描述
处理输入、射线和发送事件。
在Unity场景中EventSystem主要负责加工和处理事件。一个场景只能含有一个EventSystem。
静态属性
current | 返回当前的EventSystem。 |
属性
alreadySelecting | 如果当前已选中某个GameObject就返回true。 |
currentInputModule | 当前激活的BaseInputModule。 |
currentSelectedGameObject | 当前选择的GameObject。 |
firstSelectedGameObject | 最先被选中的GameObject。 |
isFocused | 标志着EventSystem是否认为它应该暂停,或者不基于集中状态。 |
pixelDragThreshold | 正在拖拽的软区域像素。 |
sendNavigationEvents | EventSystem是否发送导航事件(move / submit / cancel)。 |
公开方法
IsPointerOverGameObject | 给定ID的指示器是否在GameObject之上。 |
RaycastAll | 将所有已配置的BaseRaycaster投射入场景中。 |
SetSelectedGameObject | 设置当前选择的GameObject。 将触发之前选择的GameObject的OnDeselect和当前选择的OnSelect。 |
UpdateModules | 重新计算内部的BaseInputModule列表。 |
简单的使用
1、获取当前点击的UI(按钮等)
GameObject currentSelected = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject;
2、判断 鼠标/手指是否在UI上
需要注意的是:
- 需要注意如果不传入参数的话默认为pointerId = -1,即鼠标左键。
- IsPointerOverGameObject通常与nMouseDown()、Input.GetMouseButtonDown(0)或者Input.GetTouch(0).phase == TouchPhase.Began一起使用。
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class TouchExample : MonoBehaviour
{
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
Debug.Log("Touched the UI");
}
}
}
}