If Storing Dictionaries Across Saves Rebuild Them

Discuss modding questions and implementation details.
Post Reply
l3lessed
Posts: 1400
Joined: Mon Aug 12, 2019 4:32 pm
Contact:

If Storing Dictionaries Across Saves Rebuild Them

Post by l3lessed »

Maybe everyone already knows this, and I'm just some scrub coder, but I was running into an issue of trying to load saves with older versions of my mod. When I would try, I would get mismatched and null errors about keys in dictionaries built on load launch. I spent days trying to track down and understand what was wrong.

The short of it is, if you change a dictionary key between mod versions, and then a user loads the new mod version with the new dictionary with the new keys in it, it will almost certainly crash the mod. This is because, even if the current mod version is loading all the correct stuff, the old save still has stored in it the old dictionary and its keys within the saved data.

The easiest way to do remedy this is to check your dictionaries to ensure they still contain the key sets needed, and if they don't because it is an older mod version being loaded in the save, have the mod rebuild and repopulate the dictionaries with the new data needed for the new version of your mod.

Code: Select all

 public void RestoreSaveData(object saveData)
        {
            var myModSaveData = (MyModSaveData)saveData;

            //load all the previous saves dictionaries.
            iconGroupColors = myModSaveData.IconGroupColors;
            
             //ERROR CHECKER: This runs through the enum checking each marker type with the below dictionaries.
            //If one of the dictionaries below doesn't have matching marker group enums saved, it will reload the default dictionary values to stop crashes
            //This enables backwards compatibility for previous saves.
            foreach (MarkerGroups marker in (MarkerGroups[])Enum.GetValues(typeof(MarkerGroups)))
            {
                if (!iconSizes.ContainsKey(marker))
                {
                    iconSizes = new Dictionary<MarkerGroups, float>()
                    {
                        {MarkerGroups.Shops, 1f},
                        {MarkerGroups.Blacksmiths, 1f},
                        {MarkerGroups.Houses, 1f},
                        {MarkerGroups.Taverns, 1f},
                        {MarkerGroups.Utilities, 1f},
                        {MarkerGroups.Government, 1f},
                        {MarkerGroups.Friendlies, 1f},
                        {MarkerGroups.Enemies, 1f},
                        {MarkerGroups.Resident, 1f},
                        {MarkerGroups.None, 1f}
                    };
                }
            }
        }
My Daggerfall Mod Github: l3lessed DFU Mod Github

My Beth Mods: l3lessed Nexus Page

Daggerfall Unity mods: Combat Overhaul Mod

Enjoy the free work I'm doing? Consider lending your support.

Post Reply