Search Unity

Saving player data - future values & old save files

Discussion in 'Scripting' started by bernardp, Jun 6, 2019.

  1. bernardp

    bernardp

    Joined:
    Apr 28, 2017
    Posts:
    23
    I'm working on player skin unlockables and I hit one major obstacle - I have a Player class that contains info like player score, distance travelled, etc. and I could save that stuff into a JSON and then check in character selection screen if the player can use the locked character if he travelled a specific distance, has collected enough coins, etc.

    However, what if I add some new variable later on and update the game? The old save file will not contain the new variable and the game will try to access that variable that doesn't exist in old save file.

    What can I do to safely implement new variables through future game updates?
     
  2. kaarloew

    kaarloew

    Joined:
    Nov 1, 2018
    Posts:
    360
    With JSON if the key is not found from the JSON file, then the default value of variable is used.
    Code (CSharp):
    1. public int goldAmount = 10;
    In above code, if JSON does not contain key "goldAmount" then it defaults to 10

    If you want to do some overrides after deserialization then you can use e.g. OnDeserializedMethod or similar.

    Basically problems will only happen if you reuse keys (e.g. "maxHealth" goes from string to int)