运行时切换参考图像库
创作时间:2021.11.25
目的:自己学习,为了方便回顾
1.搭建环境
1.创建新的项目,命名为Image_xli_Dynamic

2.安装需要的包,这里我们需要AR Foundation和AR CoreXR Plugin包,点击右下角的install安装



3.在Hierarchy中右击,创建AR Session Origin和AR Session子系统,并将原Main Camera删除,因为子系统中自带了camera;

创建好,如下图显示:

2.创建两个参考图像库
1.在下图的路径中右击创建一个文件夹,命名为Scripts;并在创建好的文件夹中右击创建一个C#脚本,命名为ChangeImageLib;并将创建的脚本挂载在AR Session Origin上面;



2.在Assets资源中,创建一个ImageLib文件夹,并在其中创建Reference Image Library,命名为ReferenceImageLibrary_1和ReferenceImageLibrary_2.


3.在Assets文件夹中创建Texures文件夹,储存需要的材料,放置参考对象文件

4.将参考文件加入到参考图像库中

5.其他的详细尺寸设置就不赘述了,自行设置就行,单位是m,自己估计大概。

3.创建按钮和指示文本框
1.创建两个按钮,切换参考图像库;编写按钮的名字,位置之类的,可以在b站看一些视频介绍,这里就不赘述了

2.创建一个显示的文本,并调整位置

4.编写脚本文件
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class ChangeImageLib : MonoBehaviour
{
[SerializeField]
private Text mLog;
[SerializeField]
private Button firstButton, secondButton;
[SerializeField]
private GameObject prefabOnTrack;
[SerializeField]
XRReferenceImageLibrary[] mReferenceImageLibrary;
private int currentSelectedLibrary = 0;
private ARTrackedImageManager trackImageManager;
void Start()
{
trackImageManager = gameObject.AddComponent<ARTrackedImageManager>();
trackImageManager.referenceLibrary = trackImageManager.CreateRuntimeLibrary(mReferenceImageLibrary[0]);
trackImageManager.maxNumberOfMovingImages = 3;
trackImageManager.trackedImagePrefab = prefabOnTrack;
trackImageManager.enabled = true;
firstButton.onClick.AddListener(() => SetReferenceImageLibrary(0));
secondButton.onClick.AddListener(() => SetReferenceImageLibrary(1));
mLog.text = "初始化完成!";
}
public void SetReferenceImageLibrary(int selectedLibrary = 0)
{
trackImageManager.referenceLibrary = trackImageManager.CreateRuntimeLibrary(mReferenceImageLibrary[selectedLibrary]);
mLog.text = System.String.Format("切换参考图像库{0}成功!",selectedLibrary);
}
}
5.填充AR Session Origin
1.将之前创建的按钮和文本框都添加进来

2.拷贝一个prefabs,放入到Prefab On Track中

3.添加动态的图像参考库

6.设置
1.打包为安卓包,切换平台为安卓


2.对安卓平台配置:

修改默认包的名字

删除掉这个功能,不支持

取消渲染

选择安卓版本

勾选ARCore

3.插上安卓机器,Build And Run


|