Unity中,点击屏幕,判断是否点击到了场景中的物件
2022-02-18 本文已影响0人
全新的饭
实际做法
点击某界面,通过其OnPointerDown(IPointerDownHandler)获得的eventData.position,生成射线进行检测。
Ray ray = Camera.main.ScreenPointToRay(eventData.position);
Physics.Raycast(ray, out RaycastHit hit)
完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickObjTest : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public void OnPointerDown(PointerEventData eventData)
{
Ray ray = Camera.main.ScreenPointToRay(eventData.position);
if (Physics.Raycast(ray, out RaycastHit hit))
{
// TODO:针对hit提供的信息做相应处理
}
}
public void OnPointerUp(PointerEventData eventData)
{
}
}