【问题标题】:Why is my integer property not being serialized by BinaryFormatter?为什么我的整数属性没有被 BinaryFormatter 序列化?
【发布时间】:2014-09-19 18:14:02
【问题描述】:

在 Unity 上制作游戏,但我不确定这对这个问题是否重要:

创建一个MyClass 对象并将其整数宽度属性设置为100。

    MyClass obj         = new MyClass();
    obj.width = 100;
    BinaryFormatter bf  = new BinaryFormatter();
    FileStream file     = File.Create ("stuff.dat");
    bf.Serialize(file, obj);
    file.Close();

加载它。

    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open("stuff.dat");
    MyClass obj = (MyClass)bf.Deserialize(file);
    file.Close();

width 属性的默认值为 0,而不是 100。


using UnityEngine;
using System.Collections;

[System.Serializable]
public class MyClass {

    public  int             width           = 0;
    public  int             height          = 0;

}

这是为什么呢?

【问题讨论】:

  • 我的水晶球可以看出这个 width 属性原本不是类的一部分,缩进被搞砸了。使用二进制序列化很棘手,它不是版本容错的,除非您执行诸如应用 [NonSerialized] 属性这样的操作,以便仍然可以加载旧数据。那行得通。
  • obj.width = 100; ... bf.Serialize(file, data); — 你确定吗?什么是正确的,objdata
  • @OndrejTucny 是的,对不起,我不得不简化 sn-p。但问题是一样的。
  • @HansPassant:属性一直是类的一部分,我只是有奇怪的缩进倾向。
  • 嗯,值得一试。没有其他任何东西可以解释它:)

标签: c# serialization unity3d


【解决方案1】:

我知道这个问题已经 2 个月大了,但我想为其他可能偶然发现这个问题的人提供一个正确的答案,如果可以的话?

请务必注意,当您创建类的“新”版本时,它就是“新”版本。所以说在另一个班级,你做一个 MyClass mycla = new MyClass();并设置宽度 mycla.width = 100;然后你进入另一个班级并做一个 MyClass mycla = new MyClass();并尝试使用mycla.width,宽度将恢复为在主变量列表中分配的默认值。

这就是为什么您应该使用一个对象来表示您希望序列化的类中的数据。类的对象引用包含有关其变量已从默认值更改的已保存信息。

这就是我在当前游戏中处理保存的方式,它对游戏玩家来说表现良好:

    using UnityEngine;
        using System.Collections;
        using System;
        [Serializable]
        public class MyClass 
        {
            public static MyClass saveObj;
            public  int width = 0;
            public  int height = 0;
}
    //(please use another script to perform these saving and loading operations):


    public void Save()
    {
        MyClass obj = new MyClass();
        obj.width = 100;
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create ("stuff.dat");
        bf.Serialize(file, obj);
        file.Close();
    }

    public void Load()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open("stuff.dat");
        MyClass.saveObj = (MyClass)bf.Deserialize(file);
        file.Close();
        print(MyClass.saveObj.width);
    }

【讨论】:

    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2016-02-03
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多