我使用Unity的2020.3.20f1版本,我想创建一个AR应用程序。在我的应用程序中,参考图像库通过添加项目文件夹中包含的一些图像来改变运行时。
这是我的代码:'using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
using System;
using System.IO;
public class RuntimeImageLoader : MonoBehaviour
{
public ARTrackedImageManager trackedImageManager;
public string imagesFolderName = "RuntimeImages";
private void Start()
{
// Get the runtime reference image library
var referenceLibrary = trackedImageManager.referenceLibrary;
// Load images from the specified folder
var imagesFolder = $"{Application.dataPath}/{imagesFolderName}";
var imageFiles = System.IO.Directory.GetFiles(imagesFolder);
foreach (var file in imageFiles)
{
// Load the image and add it to the reference library
var imageData = System.IO.File.ReadAllBytes(file);
var texture = new Texture2D(2, 2);
texture.LoadImage(imageData);
var imageGuid = System.Guid.NewGuid();
var guidBytes = imageGuid.ToByteArray();
var serializableGuid = new UnityEngine.XR.ARSubsystems.SerializableGuid(
BitConverter.ToUInt64(guidBytes, 8),
BitConverter.ToUInt64(guidBytes, 0)
);
var runtimeImage = new XRReferenceImage(
serializableGuid,
serializableGuid,
new Vector2(texture.width, texture.height) / 1000f, // Replace with the actual size of your image
Path.GetFileNameWithoutExtension(file),
texture
);
((XRReferenceImageLibrary)referenceLibrary).Add(runtimeImage);
}
}
但是这会产生这个错误:
Assets/RuntimeImageLoader.cs(43,57):错误CS1061:'XRReferenceImageLibrary'不包含'Add'和的定义没有可访问的扩展方法'Add'接受的第一个参数类型'XRReferenceImageLibrary'可以找到(您是否缺少使用指令还是程序集引用?)
我也试过referenceLibrary.Add(runtimeImage
,但它不起作用。
如何纠正这个错误?
根据Unity文档,XRReferenceImageLibrary
在运行时是一个不可变集合。这意味着你不能更改数据。
从文档(这里):
映像库在运行时是不可变的。创造和操纵图像库通过编辑器脚本,参见扩展方法在XRReferenceImageLibraryExtensions。如果你需要改变库在运行时,参见MutableRuntimeReferenceImageLibrary。
看起来有一个类型你可以在运行时修改,叫做MutableRuntimeReferenceImageLibrary。但是不能保证你的AR是否支持它。我建议查看这些类型的文档,以确定您的AR是否支持它以及如何检索它。