确定光标是否位于场景中的图形元素上方。请参阅:BaseRaycaster。
这可用于确定光标是否位于场景中的图形元素上方。它接受鼠标指针事件数据作为参数。请确保层级视图中具有 EventSystem。如果没有,请转到 Create >UI >Event System。 一些常见用法包括:设置自己的自定义 UI 系统;判断鼠标悬停在不可自动选择的文本或图像上的时间;UI 单击和拖动操作;等等。
//Attach this script to your Canvas GameObject. //Also attach a GraphicsRaycaster component to your canvas by clicking the Add Component button in the Inspector window. //Also make sure you have an EventSystem in your hierarchy.
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections.Generic;
public class GraphicRaycasterRaycasterExample : MonoBehaviour { GraphicRaycaster m_Raycaster; PointerEventData m_PointerEventData; EventSystem m_EventSystem;
void Start() { //Fetch the Raycaster from the GameObject (the Canvas) m_Raycaster = GetComponent<GraphicRaycaster>(); //Fetch the Event System from the Scene m_EventSystem = GetComponent<EventSystem>(); }
void Update() { //Check if the left Mouse button is clicked if (Input.GetKey(KeyCode.Mouse0)) { //Set up the new Pointer Event m_PointerEventData = new PointerEventData(m_EventSystem); //Set the Pointer Event Position to that of the mouse position m_PointerEventData.position = Input.mousePosition;
//Create a list of Raycast Results List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position m_Raycaster.Raycast(m_PointerEventData, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray foreach (RaycastResult result in results) { Debug.Log("Hit " + result.gameObject.name); } } } }