工程目标
在HoloLens2中实现读取眼镜中的本地文件,由于HoloLens中没有磁盘的概念,所以在本工程中使用的方法是KnownFolder
,通过该方法访问位于眼镜Picture、Video、Music及Document
文件夹下的文件。
实现方法
存放文件
本工程中使用的是KnownFolders.PicturesLibrary方法,将需要读取的文件放入HoloLens中的Picture文件夹下:
文件内容为123ReadSuccess
:
编写脚本
该脚本实现了将读取到的文件数据显示在场景中的功能,其中变量AsyncContentTest
显示的是数据传回主进程调用,ReadContentTest
显示的是在异步线程中的调用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System.Text;
#if WINDOWS_UWP//UWP下编译
using Windows.Storage;
using System.Threading.Tasks;
using System;
using System.Threading;
#endif
public class UWP_KnownFolders : MonoBehaviour
{
public Text ReadContentTest;
public Text AsyncContentTest;
bool isReadBegin = false;
string list = "AsyncFail";
string fileName = "ReadTest.txt";
// Start is called before the first frame update
void Start()
{
}
public void ReadBegin()
{
ReadContentTest.text = "Fail";
list = OpenFileForRead(fileName);
AsyncContentTest.text = list;
}
private Stream OpenFileForRead(string fileName)
{
string stlName = "Wait";
Stream fileStreamAsync = null;
#if WINDOWS_UWP
Task task = new Task(
async () => {
//读取文件内容
StorageFolder modelFolder = KnownFolders.PicturesLibrary;
IStorageItem fileExist = await modelFolder.TryGetItemAsync(fileName);
if(fileExist != null){
StorageFile modelFile = await modelFolder.GetFileAsync(fileName);
fileStreamAsync = await modelFile.OpenStreamForReadAsync();
//文本内容显示
byte[] data = new byte[fileStreamAsync.Length];
fileStreamAsync.Read(data, 0, 80);
stlName = Encoding.UTF8.GetString(data);
}
else
stlName = "none";
});
task.Start();
#endif
while (stlName == "Wait")
{
}
return fileStreamAsync;
}
// Update is called once per frame
void Update()
{
}
}
创建场景
①在场景中创建两个UI->text
②将UWP_KnownFolders脚本挂在GameObject下,选择text
显示
将场景生成UWP应用后,将应用部署到眼镜中,点击触发Read Begin()
函数的按钮,文本中的内容显示在场景中。