我使用的是 Unity 2021.3.22f1 和 AR Foundation 的 4.2.7 版本。 我已经在我的场景中添加了 AR Session 和 AR Session Origin,以及 AR Tracked Image Manager 作为 AR Session Origin 的一个组件。
我想创建一个 MutableRuntimeReferenceImageLibrary,它在运行时动态添加包含在项目文件夹中的图像。
我写了这段代码:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class ImageLibraryManager : MonoBehaviour
{
public ARTrackedImageManager trackedImageManager;
public string imageFolderPath;
void Start()
{
// Create a list to hold XRReferenceImage objects
var imageList = new List<XRReferenceImage>();
// Get the files in the image folder
var imageFiles = System.IO.Directory.GetFiles(imageFolderPath);
// Loop through the image files and add them to the list
foreach (var imageFile in imageFiles)
{
// Load the image from the file
var imageBytes = System.IO.File.ReadAllBytes(imageFile);
var texture = new Texture2D(2, 2);
texture.LoadImage(imageBytes);
var newGuid = System.Guid.NewGuid();
var guidBytes = newGuid.ToByteArray();
var image = new XRReferenceImage(
// Use a new guid for each image
new SerializableGuid(
(ulong)(guidBytes[3] << 24 | guidBytes[2] << 16 | guidBytes[1] << 8 | guidBytes[0]),
(ulong)(guidBytes[7] << 24 | guidBytes[6] << 16 | guidBytes[5] << 8 | guidBytes[4])
),
// Use an empty guid for the second parameter
SerializableGuid.empty,
// Set the size of the image in meters
new Vector2(texture.width, texture.height) / 1000f,
// Set the name of the image
System.IO.Path.GetFileNameWithoutExtension(imageFile),
// Set the texture of the image
texture
);
imageList.Add(image);
}
// Create a new MutableRuntimeReferenceImageLibrary and assign it to the ARTrackedImageManager
var imageLibrary = trackedImageManager.CreateRuntimeLibrary() as MutableRuntimeReferenceImageLibrary;
foreach (var image in imageList)
{
// Add each image to the image library
imageLibrary.AddReferenceImage(image);
}
trackedImageManager.referenceLibrary = imageLibrary;
}
}
但是,这给了我这个错误:
Assets/ImageLibraryManager.cs(53,26): error CS1061: 'MutableRuntimeReferenceImageLibrary' does not contain a definition for 'AddReferenceImage' and no accessible extension method 'AddReferenceImage' accepting a first argument of type 'MutableRuntimeReferenceImageLibrary' could be found (are you missing a using directive or an assembly reference?)
我已经尝试过其他方法,如“Add”或“AddImage”,但它总是给我同样的错误。
你能帮我解决我的问题并创建这种类型的 MutableRuntimeReferenceImageLibrary 吗?
谢谢你
查看评论。我认为您可能需要做的是通过创建自定义类来继承 RuntimeReferenceImageLibrary。然后实例化这个类的一个对象并调用Add方法。这个类并不完美,所以你需要学习如何使用面向对象编程的 C# 创建子类。
public class CustomImageLibrary : RuntimeReferenceImageLibrary
{
public int count { get; }
public CustomImageLibrary()
{
Console.WriteLine("Constructor.");
}
protected XRReferenceImage GetReferenceImageAt(int index)
{
}
}
现在实例化名为 imageLibrary 的对象变量。
CustomImageLibrary imageLibrary = new CustomImageLibrary();
现在添加您的图片。