【问题标题】:Unity and Hololens: Reading non-text file exceptionUnity 和 Hololens:读取非文本文件异常
【发布时间】:2019-01-28 20:19:38
【问题描述】:

[已编辑] 首先我必须道歉,我刚刚注意到我粘贴的一些代码,因为我们用于读取 png 文件的代码在 .net 后端也工作(txt 读取对两者都有效,.net和 il2cpp,如前所述)。调用堆栈来自不同的异常。现已更正

我们正在为 Microsoft Hololens 开发一个 XR 应用程序,该应用程序涉及读取 txt 和二进制文件(后者作为字节数组作为 Unity 纹理由 Texture2D.LoadImage 加载)。因为我们需要为用户提供一种简单的方法来更改/修改文件,所以这两个文件都位于 hololens 的 3D Objects 文件夹中。

在我们最近不得不将脚本后端从 .net 更改为 il2cpp 之前,一切都正常运行;从那时起,每当我们尝试读取我们的 png 文件时,我们都会发现错误,尽管 txt 仍然可以读取,而我们的 .net 源代码没有任何更改。

我们正在像这样读取我们的文本文件(正常工作):

    Windows.Storage.StorageFolder objectsFolder = Windows.Storage.KnownFolders.Objects3D;
    Windows.Storage.StorageFile csvFile = await objectsFolder.GetFileAsync(oneFile);
    string contentText = await Windows.Storage.FileIO.ReadTextAsync(csvFile);

对于 PNG,我们尝试了几种不同的方法,包括最简单的 File.ReadAllBytes( pngFile.Path);(它适用于 .net,但不适用于 il2cpp)、FileStream 和其他方法,但它们总是在某些时候失败。最后一个是这样的:

     Windows.Storage.StorageFolder pngObjectsFolder = Windows.Storage.KnownFolders.Objects3D;
     Windows.Storage.StorageFile pngFile = await pngObjectsFolder.GetFileAsync(i.ToString() + ".png");

     Windows.Storage.Streams.IBuffer buffer = await Windows.Storage.FileIO.ReadBufferAsync(pngFile);
     Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);


     dataReader.ReadBytes (fileData);

...抛出此异常:

抛出异常:“System.NullReferenceException”在 程序集-CSharp.dll

并且在调用堆栈中只有这个:

在 CsvReader.d__4.MoveNext()

所以在我们看来,我们的 dataReader 保持为空,但我们并不真正了解发生了什么,也不知道如何防止它。谁能提供一些关于阅读此类文件的建议或想法?

问候!

【问题讨论】:

  • 是否还有来自异常的消息(不仅仅是调用堆栈)?
  • 我一直在审查和清理问题以修复问题中的一些内容并粘贴异常,我发现了我们的错误并使其正常工作。谢谢,朋友!

标签: c# file unity3d hololens il2cpp


【解决方案1】:

经过更多的工作,我们终于找到了为什么这不起作用......这很尴尬。碰巧数组'fileData'没有初始化。源代码应该是这样的:

        Windows.Storage.StorageFolder pngObjectsFolder = Windows.Storage.KnownFolders.Objects3D;
        Windows.Storage.StorageFile pngFile = await pngObjectsFolder.GetFileAsync(i.ToString() + ".png");             
        Windows.Storage.Streams.IBuffer buffer = await Windows.Storage.FileIO.ReadBufferAsync(pngFile);                      
        Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer (buffer);

        fileData = new byte[buffer.Length];     
        dataReader.ReadBytes (fileData);

此时,我们将 fileData 中的 png 文件作为一个字节数组,我们可以随意使用它做任何我们需要的事情。在我们的例子中,将其加载到 Unity 3d 纹理对象中:

        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData);

因此,如果其他人在使用 il2cpp 后端加载二进制文件时遇到困难,这似乎是一种可靠的方法。

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 2012-10-07
    相关资源
    最近更新 更多