开启与关闭平面检测
准备工作
首先搭建好基本环境,在AR Session Origin下添加一个AR Plane Manager对象,并添加一个预制体AR Default Plane到AR Plane Manager对象的Plane Prefab属性下(这一部分在Unity配置Android开发环境下有介绍不再记录)Unity配置Android开发环境与第一个Demo
![image-20220116123721232](https://img-blog.csdnimg.cn/img_convert/72688a24e29ddf3b66658dad81df16fd.png)
添加脚本
AR Plane Manager 负责管理检测平面相关工作,其有一个属性 enabled,设置 enabled=true 则是开启了平面检测,设置 enabled=false 则是关闭了平面检测,因此, 我们可以非常方便的用代码控制平面的检测与关闭。前文我们也学习到,ARPlaneManager 并不负责检 测到的平面的可视化渲染,因此,在关闭平面检测后我们还应该取消已检测到的平面的显示。
- 在Scripts文件夹下创建一个C#脚本,命名为
PlaneDetectionController - 将脚本挂载到与AR Plane Manager组件相同的场景对象上
- 添加一个UI-Button,将按钮与脚本中的Toggle Plane Detection()函数绑定
![image-20220116124932616](https://img-blog.csdnimg.cn/img_convert/70672bd5a02d355e7f139855b23de14a.png)
![image-20220116125204717](https://img-blog.csdnimg.cn/img_convert/6cee4fdd13db6e1e049fcc1e19261cd3.png)
![image-20220116125320839](https://img-blog.csdnimg.cn/img_convert/13df1ee8d8a359673ebd651ab7aa3ffb.png)
![image-20220116125528438](https://img-blog.csdnimg.cn/img_convert/f99fad006c282496bf29c58b38c7936d.png)
![image-20220116125637054](https://img-blog.csdnimg.cn/img_convert/df5cc296290b3f4b1ed2fcb77d5ab03b.png)
![image-20220116130259718](https://img-blog.csdnimg.cn/img_convert/09b7c69db571378d2ba47bc1bf3f3d91.png)
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
namespace UnityEngine.XR.ARFoundation.Samples
{
[RequireComponent(typeof(ARPlaneManager))]
public class PlaneDetectionController : MonoBehaviour
{
[Tooltip("The UI Text element used to display plane detection messages.")]
[SerializeField]
Text m_TogglePlaneDetectionText;
public Text togglePlaneDetectionText
{
get { return m_TogglePlaneDetectionText; }
set { m_TogglePlaneDetectionText = value; }
}
public void TogglePlaneDetection()
{
m_ARPlaneManager.enabled = !m_ARPlaneManager.enabled;
string planeDetectionMessage = "";
if (m_ARPlaneManager.enabled)
{
planeDetectionMessage = "Disable Plane Detection and Hide Existing";
SetAllPlanesActive(true);
}
else
{
planeDetectionMessage = "Enable Plane Detection and Show Existing";
SetAllPlanesActive(false);
}
if (togglePlaneDetectionText != null)
togglePlaneDetectionText.text = planeDetectionMessage;
}
void SetAllPlanesActive(bool value)
{
foreach (var plane in m_ARPlaneManager.trackables)
plane.gameObject.SetActive(value);
}
void Awake()
{
m_ARPlaneManager = GetComponent<ARPlaneManager>();
}
ARPlaneManager m_ARPlaneManager;
}
}
添加事件的疑难:
UGUI中Button和Toggle 添加动态事件
Unity - 方法绑定到Button.OnClick
演示效果
https://www.bilibili.com/video/BV1sZ4y1f77G/
|