Mama Tate
Mama Tate

Reputation: 283

Serializing a field with protobuf results in a 0 bytes data file

I am trying to serialize a field in protobuf, but the result is 0 bytes file. Problem lies when i try to change the field firstRun in GameData:

[ProtoContract, Serializable]
public class GameData
{
[ProtoMember(1)]
public bool firstRun = true;
}

public class PersistentDataManager 
{

public bool FirstRun { get { return GameData.firstRun; } private set { GameData.firstRun = value; } }
public GameData GameData { get; private set; }

private const string DataFileName = "GameData.dat";
private ISerializer m_serializer;

private void Awake()
{
    // Selecting protobuf as our default serializer.
    m_serializer = new ProtobufSerializer();
    LoadData();
}

public void SaveData()
{
    m_serializer.Serialize<GameData>(Application.persistentDataPath + "/" + DataFileName, GameData);
}

public void LoadData()
{
    if (File.Exists(Application.persistentDataPath + "/" + DataFileName))
    {
        GameData = m_serializer.Deserialize<GameData>(Application.persistentDataPath + "/" + DataFileName);
    }
    else
    {
        GameData = new GameData();
    }
}

public void DeleteData()
{
    string filePath = Application.persistentDataPath + "/" + DataFileName;

    if (File.Exists(filePath))
    {
        File.Delete(filePath);
    }
}

public void ResetToFirstRun()
{
    FirstRun = true;
}

private void FirstTimeRunCheck()
{
    if (FirstRun == true)
    {
        FirstRun = false;
    }
}

private void OnDestroy()
{
    FirstTimeRunCheck(); // If i remove this line protobuf serializes properly.
    SaveData();
}
}

So when i remove the FirstTimeRunCheck() method protobuf serializes the data, but when the method gets called in OnDestroy() protobuf does not serializes it. Tried using the BinaryFormatter to see if something else is wrong, but the file get's serialized properly. Maybe i never understood how protobuf works at all. Can somebody help me out and write where the problem might be?

Upvotes: 2

Views: 642

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

It is serializing properly. Simply: zero bytes is a perfectly legal serialization length for protobuf. Specifically, this relates to "implicit zero defaults" - a (now much regretted) implementation specific feature of protobuf-net v1. In your case, zero (aka false) is not the default, so you'll need to help it a little:

private bool firstRun = true;
[ProtoMember(1), DefaultValue(true)]
public bool FirstRun {
    get { return firstRun; }
    set { firstRun = value; }
}

Upvotes: 3

Related Questions