1.需要判断的地方
//UI遮挡3D物体射线
if (ZheDang.Instance.CheckGuiRaycastObjects())
{
return;
}
2.独立脚本
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
public class ZheDang : MonoBehaviour
{
public static ZheDang Instance;
//下面是用来UI事件和射线
EventSystem eventSystem;
GraphicRaycaster RaycastInCanvas;//Canvas上有这个组件
void Awake()
{
Instance = this;
RaycastInCanvas = this.gameObject.GetComponent<GraphicRaycaster>();//这个脚本要绑定到Canvas
}
void Update()
{
if (CheckGuiRaycastObjects()) return;//如果射线检测到UI上直接返回
}
public bool CheckGuiRaycastObjects()//测试UI射线
{
PointerEventData eventData = new PointerEventData(eventSystem);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> list = new List<RaycastResult>();
RaycastInCanvas.Raycast(eventData, list);
//Debug.Log(list.Count);
return list.Count > 0;
}
}
//注意:GraphicRaycaster组件默认在canvas上就有的,所以将上面脚本绑定到Canvas上就OK。
//然后运行看到当点击按钮时3D场景不会受到影响了。
网友评论