Unity 中的反序列化性能下降

Deserialization slow performance in Unity

我正在Unity中制作一个3D模拟器。
对于这个模拟器,我需要一些存储在 Serializable 对象中的数据。
这个对象是在我制作的一个DLL文件中定义的。
我用这段代码反序列化它:

public class myObject
{
    static public myObject LoadFromFile(String Path)
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        System.IO.FileStream FS = new System.IO.FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
        myObject Result = BF.Deserialize(FS) as myObject;
        FS.Close();
        return Result;
    }
}

我的 unity 程序引用了包含 'myObject' 定义的 class 库。
如果我 运行 来自 Unity 的反序列化函数,这个过程需要 35.080 秒。

如果我在一个 windows 应用程序中 运行 这个,我为测试目的创建并引用同一个 class 库并打开同一个文件,这个过程只需要 0.260秒.

即使我 运行 这个过程是异步的,在 Unity 中也需要很长时间。

我想知道为什么当我 运行 来自 Unity 的这段代码时需要那么多时间? 如果有什么我可以做的?

提前致谢,
马丁

我不完全理解你的问题。您要访问的 class 在您的 .dll 文件中?如果是这样——您的 class 定义位于何处并不重要。您的数据存储在哪里以及如何存储?如果您想将数据永久存储在硬盘上,您可以轻松地使用 Json.NET 并将数据存储为 .json 文件。您尝试从哪种方法以及何时在 unity 中加载数据?

此外,如果您打开一个文件流,您也应该在读完后再次关闭它。您还可以查看一些编码约定,例如 here

我不知道为什么会这样,但您可以尝试实现 ISerializable 接口,自己序列化您的成员,看看 unity 是否仍然那么慢。

您将需要实现 GetObjectData 和一个采用 SerializationInfo 和 StreamingContext 的受保护构造函数。 GetObjectData 用于将对象放在序列化流上,构造器用于......呃......构造。

public class MyObject : ISerializable
{
  private bool somemember;

  protected Complaint(SerializationInfo info, StreamingContext context)
  {
    somemember = info.GetBoolean("b");
  }

  [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
  public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("b", somemember);
  }
}

希望对您有所帮助!