1.把ui都归为一个层 级 3dobj也归为其他层级
2.写一个代码 挂载一个全局空物体上 通过射线检测
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickHandler : MonoBehaviour
{
[Header("射线设置")]
public LayerMask interactableLayers; // 设置为 Interactable 层
public float maxDistance = 100f;
void Update()
{
if (Input.GetMouseButtonDown(0) || IsTouchBegan())
{
// 第一步:检测是否点击在UI上
if (IsPointerOverUI())
{
Debug.Log("点击在UI上,不处理3D物体");
return;
}
// 第二步:处理3D物体点击
Handle3DClick();
}
}
bool IsTouchBegan()
{
return Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began;
}
bool IsPointerOverUI()
{
// 标准检测方法(兼容多平台)
if (EventSystem.current.IsPointerOverGameObject())
return true;
// 移动端多点触摸检测
if (Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began &&
EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
return true;
}
}
}
return false;
}
void Handle3DClick()
{
Ray ray = Camera.main.ScreenPointToRay(GetInputPosition());
RaycastHit hit;
if (Physics.Raycast(ray, out hit, maxDistance, interactableLayers))
{
Debug.Log($"点击到3D物体:{hit.collider.name}");
hit.collider.GetComponent<IInteractable>()?.OnClick();
}
}
Vector2 GetInputPosition()
{
return Input.touchCount > 0 ?
Input.GetTouch(0).position :
(Vector2)Input.mousePosition;
}
}
// 3D物体交互接口
public interface IInteractable
{
void OnClick();
}
3.创建要触发事件的3dobj 事件脚本 并将这个脚本挂载3dobj上
using UnityEngine;
public class InteractiveCube : MonoBehaviour, IInteractable
{
public void OnClick()
{
GetComponent<Renderer>().material.color = Random.ColorHSV();
Debug.Log("3D立方体被点击!");
}
}
4.运行即可