【问题标题】:Text file in/out on Hololens works for writing but not reading (Unity,Hololens,C#)Hololens 上的文本文件输入/输出可用于写入但不能用于读取(Unity、Hololens、C#)
【发布时间】:2018-03-22 11:51:11
【问题描述】:

我正在尝试在 HoloLens 上发现基本文件输入/输出。我正在使用以下代码:

public class FileInOut : MonoBehaviour {

    string plainText = "";
    TextMesh textmesh;

    // Use this for initialization
    void Start () {

        textmesh = GameObject.Find ("Text").GetComponent<TextMesh>();
        //test if Text changes normally
        textmesh.text = "Hallo";

        //create the text file and put text into it
        #if WINDOWS_UWP        

        Task task = new Task(async () =>
        {                              
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile textFileForWrite = await storageFolder.CreateFileAsync("LocalText.txt");
            await FileIO.WriteTextAsync(textFileForWrite, "Test Start");
        });
        task.Start();
        task.Wait();

        #endif
    }

    // Update is called once per frame
    void Update () {
        //Read the text file and change the text of 3D text to it (not working)
        #if WINDOWS_UWP        

        Task task = new Task(async () =>
        {                              
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile textFileforRead = await storageFolder.GetFileAsync("LocalText.txt");
            plainText = await FileIO.ReadTextAsync(textFileforRead);
            textmesh.text = plainText;
        });
        task.Start();
        task.Wait();

        #endif
    }
}

Start() 函数中编写的代码似乎可以工作,我可以通过设备门户访问文本文件。但是我的 3D 文本对象的文本不会变成“测试开始”(尽管它在文本文件中)。

知道为什么写作有效而阅读无效吗?

【问题讨论】:

  • 有没有试过将plainText设置为public,看看赋值是否正确?
  • HoloLens 在读取和写入文件时有一些奇怪的地方。我发现除非你使用Windows.Storage.KnownFoldersApplication.persistentDataPath 作为文件路径,否则它不会太喜欢它。

标签: c# unity3d file-io hololens


【解决方案1】:

两件事:

  1. 您只能从Application.persistentDataPath 可靠地读/写。您应该为路径添加前缀:

var path = Path.Combine(Application.persistentDataPath, "MyPath.txt");

  1. 如果您只是同步读取和写入字节,我建议您只使用File 操作。

写作:

File.WriteAllBytes(Encoding.UTF8.GetBytes(text));

阅读:

Encoding.UTF8.GetString(File.ReadAllBytes(path));

UWP 和 .NET Framework 支持此 API,因此您也不需要条件编译指令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2023-04-09
    • 2021-05-07
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多