常见的有3种情况:
1.点击UI,后面的3D物体不需要响应
2.点击了UI,后面的3D物体同时也需要响应
3.点击了鼠标右键,在点到UI的时候不需要响应
以上几个问题,其实通过 EventSystem.current.IsPointerOverGameObject() 这个方法就能解决掉。
这个方法的含义就是判断当前鼠标是否点击到了UI,并返回布尔值。实现方式大概是这样的:
bool IsPointerOverGameObject()
{
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
graphic.Raycast(eventData, results);
return results.Count > 0;
}
但是这里提出一种新的方式。
我们的3D物体的点击触发事件,一般是用的OnMouseDown 这种自带的方法,
其实也可用点击UI的一套系统,
和UI的点击是一样的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine