一.环境
案例网址 : https://github.com/Unity-Technologies/arfoundation-samples.git
官方文档网址 : https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@2.2/api/UnityEngine.XR.ARFoundation.html
Unity版本 : 2019.3.0
SDK版本 :
![](https://img.haomeiwen.com/i17787668/48fcee3a953d8786.png)
二.代码解析
1.功能
停止/启动平面检测并隐藏/显示已检测平面
2.项目结构
![](https://img.haomeiwen.com/i17787668/5f04b1cbe01da525.png)
主要脚本都在AR Session Origin上:
![](https://img.haomeiwen.com/i17787668/d5fbd0db1df34dd1.png)
3.代码解析
其实原理非常简单,TogglePlaneDetection物体的Toggle点击事件是PlaneDetectionController脚本中的TogglePlaneDetection函数,此函数中首先置反ARPlaneManager.enabled,之后设置已识别平面的可见性
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
/// <summary>
///这个例子演示了如何切换平面检测,
///并隐藏或显示现有的平面。
/// </summary>
[RequireComponent(typeof(ARPlaneManager))]
public class PlaneDetectionController : MonoBehaviour
{
[Tooltip("用于显示平面检测消息的UI文本元素。")]
[SerializeField]
Text m_TogglePlaneDetectionText;
/// <summary>
/// The UI Text element used to display plane detection messages.
/// </summary>
public Text togglePlaneDetectionText
{
get { return m_TogglePlaneDetectionText; }
set { m_TogglePlaneDetectionText = value; }
}
/// <summary>
///切换平面检测和平面可视化。
/// </summary>
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;
}
/// <summary>
/// 设置识别平面的可见性
/// </summary>
/// <param name="value">Each planes' GameObject is SetActive with this value.</param>
void SetAllPlanesActive(bool value)
{
foreach (var plane in m_ARPlaneManager.trackables)
plane.gameObject.SetActive(value);
}
void Awake()
{
m_ARPlaneManager = GetComponent<ARPlaneManager>();
}
ARPlaneManager m_ARPlaneManager;
}
![](https://img.haomeiwen.com/i17787668/4eca4da34eb71a37.png)
网友评论