C#Serialization Woes - Int Array未正确保存/返回

时间:2016-07-27 11:19:03

标签: c# serialization unity3d

我希望有人可以告诉我我做错了什么,以及纠正它的最佳方法(或指向我的链接)。

我使用以下代码/类来使用BinaryFormatter序列化我的数据。由于某种原因,TileData类中的第一个int(Corners)一直反序列化为255。我已经验证了数据在序列化之前是否正确保存在结构中,因此序列化和反序列化之间的某些事情发生在数据中,并且我不确定为什么或如何检查它是哪一端。

有什么想法吗?

[Serializable]
public class GameSaveData
{
    public readonly string Name;
    public readonly int[] LevelSettings;
    public readonly int[] GTime;
    public readonly ChunkData[] Data; 

    public GameSaveData(string _name, int[] _settings, int[] _time, ChunkData[] _chunks)
    {
        Name = _name;
        LevelSettings = _settings;
        GTime = _time;
        Data = _chunks;
    }
}

[Serializable]
public class TileData
{
    public readonly int Corners;
    public readonly int TypeID;
    public readonly int[] FloorSpecs; // 0 -- Floor Missing, 1 - Floor Type ID, 2 -- SubFloor Type

    public TileData(int _c, int _t, int[] _floorSpecs)
    {
        Corners = _c;
        TypeID = _t;
        FloorSpecs = _floorSpecs;
    }
}

[Serializable]
public class ChunkData
{
    public readonly int[] Position;
    public readonly TileData[] Data;

    public ChunkData(Vector3 _pos, TileData[] _data)
    {
        Position = new int[] { (int)_pos.x, (int)_pos.y, (int)_pos.z };
        Data = _data;
    }
}

2 个答案:

答案 0 :(得分:1)

我不确定这一点,但事实并非变量被标记为只读,以防止正确的反序列化?

为什么不使用Unity中提供的JsonUtility类?毕竟,Json可以更广泛地使用。

答案 1 :(得分:0)

serizable Class必须是带有无参数构造函数的简单容器 (仅限Xml序列化)。

看看this post

像这样的东西

[Serializable]
public class GameSaveData
{
    public string Name { get; set; }
    public int[] LevelSettings { get; set; }
    public int[] GTime { get; set; }
    public ChunkData[] Data { get; set; }

    private GameSaveData() 
    {
        // parameter less constrctor
    }

    public GameSaveData(string _name, int[] _settings, int[] _time, ChunkData[] _chunks)
    {
        Name = _name;
        LevelSettings = _settings;
        GTime = _time;
        Data = _chunks;
    }
}

[Serializable]
public class TileData
{
    public int Corners { get; set; }
    public int TypeID { get; set; }
    public int[] FloorSpecs { get; set; } // 0 -- Floor Missing, 1 - Floor Type ID, 2 -- SubFloor Type

    public TileData()
    {
        // parameter less constrctor            
    }

    public TileData(int _c, int _t, int[] _floorSpecs)
    {
        Corners = _c;
        TypeID = _t;
        FloorSpecs = _floorSpecs;
    }
}

[Serializable]
public class ChunkData
{
    public readonly int[] Position { get; set; }
    public readonly TileData[] Data { get; set; }

    public ChunkData()
    {
        // parameter less constrctor                        
    }

    public ChunkData(Vector3 _pos, TileData[] _data)
    {
        Position = new int[] { (int)_pos.x, (int)_pos.y, (int)_pos.z };
        Data = _data;
    }
}