Ordinal of enum affecting BinaryFormatter deserialization?

James McMahon

I am hitting a strange issue with score serialization in my game.

I have a LevelHighScore class:

[System.Serializable]
public class LevelHighScores
{
    readonly Dictionary<Level, ModeScores> scores;
    // clipped out the rest for simplicity
}

With a enum key, Level.

I recently added some new levels to my game, but instead of adding the new levels to the end of the enum, I added the new enums in alphabetical order. Now when I load the game my new levels have existing scores associated with them, making me think that the ordinal of the enums are having an effect on the serialization / deserialization.

I want to avoid to avoid this issue when adding levels in the future. I also don't want to have to remember to only add levels to the end of the enum.

Is there a way to ensure that enum are deserialized consistently, even when retroactively adding new values?

James McMahon

I ended up following dbc's suggestion and adding explicit values to the enum.

So, I changed Level from,

public enum Level
{
    Aquarium,
    Crescendo,
    HungarianDance,
    MapleLeafRag,
}

To

// NOTE: the numbers here don't represent order,
// they are just to ensure proper serialization
public enum Level
{
    AmazingPlan = 4, // new level
    Aquarium = 0,
    Crescendo = 1,
    HungarianDance = 2,
    MapleLeafRag = 3,
}

This was a nice simple solution to my problem, though I think for non-Unity projects Scott Hannen's answer is probably the way to go.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related