unity 新input system 鼠标点在ui上检测的两种方法
哪种有用就用哪种。EventSystem.current.IsPointerOverGameObject()有可能不好使。
using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.InputSystem; using UnityEngine.UI; public class GameManager : MonoBehaviour { //拖拽获取 public GraphicRaycaster m_Raycaster; //拖拽获取 public EventSystem m_EventSystem; private PointerEventData m_PointerEventData; public void OnMouseDown(InputAction.CallbackContext context) { if (context.phase == InputActionPhase.Performed) {//方法1 //Set up the new Pointer Event PointerEventData m_PointerEventData = new PointerEventData(m_EventSystem); //Set the Pointer Event Position to that of the mouse position m_PointerEventData.position = Mouse.current.position.ReadValue(); //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); if (results.Count > 0) { Debug.Log("UI"); } //方法2 if (!EventSystem.current.IsPointerOverGameObject()) { Vector2 mousePosition = Mouse.current.position.ReadValue(); Ray mouseRay = Camera.main.ScreenPointToRay(mousePosition); Physics.Raycast(mouseRay, out RaycastHit raycast); Debug.Log(raycast.collider.name); } else { Debug.Log("ui"); } } } }