在使用hololen2 +vs2019+unity2019 anchorWorldAnchorTransferBatch 存储空间锚点,本地化,序列化的空间锚点的txt 文件只有system.Byte[] 这几个字,显然序列化出错了吧。如何解决呢?
场景如下:
一下是代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
using UnityEngine.XR.WSA.Sharing;
using System.IO;
using TMPro;
#if WINDOWS_UWP
using Windows.Storage;
#endif
public class LocalWorldAnchor : MonoBehaviour
{
public GameObject rootGameObject;
private UnityEngine.XR.WSA.WorldAnchor gameRootAnchor;
private int retryCount = 3; //解析锚点重试次数
private byte[] importedData; //存储的锚点数据
public TextMeshPro text;
void Start()
{
gameRootAnchor = rootGameObject.GetComponent<UnityEngine.XR.WSA.WorldAnchor>();
if (gameRootAnchor == null)
{
gameRootAnchor = rootGameObject.AddComponent<UnityEngine.XR.WSA.WorldAnchor>();
}
}
//// 导出锚点
public void ExportGameRootAnchor()
{
WorldAnchorTransferBatch transferBatch = new WorldAnchorTransferBatch();
transferBatch.AddWorldAnchor("gameRoot", this.gameRootAnchor);
WorldAnchorTransferBatch.ExportAsync(transferBatch, OnExportDataAvailable, OnExportComplete);
}
private void OnExportDataAvailable(byte[] data)
{
StartCoroutine(SaveDataToDisk(data));
//TransferDataToClient(data); 通过网络传输到其他设备
}
IEnumerator SaveDataToDisk(byte[] data)
{
string filename = "SavedWorldAnchorID.txt";
string path = Application.persistentDataPath;
#if WINDOWS_UWP
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
path = storageFolder.Path.Replace('\\', '/') + "/";
#endif
string filePath = Path.Combine(path, filename);
File.WriteAllText(filePath, data.ToString());
//Debug.Log($"成功保存世界锚点到:'{filePath}'");
text.text = "Succeed ";
yield return 0;
}
private void OnExportComplete(SerializationCompletionReason completionReason)
{
if (completionReason != SerializationCompletionReason.Succeeded)
{
Debug.Log("序列化成功!");
}
else
{
Debug.Log("序列化数据失败!");
}
}
/// 导入锚点
public void ImportWorldAnchor()
{
StartCoroutine(GetDataFromDisk());
}
IEnumerator GetDataFromDisk()
{
string filename = "SavedWorldAnchorID.txt";
string path = Application.persistentDataPath;
#if WINDOWS_UWP
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
path = storageFolder.Path.Replace('\\', '/') + "/";
#endif
string filePath = Path.Combine(path, filename);
string worldAnchor = File.ReadAllText(filePath);
importedData = System.Text.Encoding.Default.GetBytes(worldAnchor);
WorldAnchorTransferBatch.ImportAsync(importedData, OnImportComplete);
yield return 0;
}
private void OnImportComplete(SerializationCompletionReason completionReason, WorldAnchorTransferBatch deserializedTransferBatch)
{
if (completionReason != SerializationCompletionReason.Succeeded)
{
Debug.Log("序列化失败: " + completionReason.ToString());
if (retryCount > 0)
{
retryCount--;
WorldAnchorTransferBatch.ImportAsync(importedData, OnImportComplete);
}
return;
}
this.gameRootAnchor = deserializedTransferBatch.LockObject("gameRoot", this.rootGameObject);
}
}