ISaveUpgradable

Summary: Update loaded data in code after an older version is read.

Description

Implement ISaveUpgradable on a saved type to fix up values after an older version loads, for example to fill a field added in the new version. No registration is needed.

Save System calls OnUpgrade on the main thread when the saved data version is lower than the type’s SaveVersion. It runs once, after any upgrade steps, with the original saved version. If OnUpgrade throws, the load returns SerializationError.

Namespace Gley.SaveSystem.

Declaration

C#
public interface ISaveUpgradable

Members

MemberTypeDescription
OnUpgrade—void OnUpgrade(int fromVersion)
Called after an older save is read. fromVersion is the version the data was saved with.

Example

Create LoadUpgradableSettings.cs and attach it to an active GameObject. Enter Play mode to load the settings. When the save was written as version 1, the SFX volume starts at the saved music volume. See Changing your save data after release for the full workflow.

C#
using System;
using Gley.SaveSystem;
using UnityEngine;

public class LoadUpgradableSettings : MonoBehaviour
{
    private void Start()
    {
        LoadResult<AudioSettingsData> result = API.Load<AudioSettingsData>("audio-settings");
        Debug.Log($"Load status: {result.Status}, SFX volume: {result.Data.SfxVolume}", this);
    }

    [Serializable, SaveVersion(2)]
    private class AudioSettingsData : ISaveUpgradable
    {
        [SerializeField] private float _musicVolume = 0.8f;
        [SerializeField] private float _sfxVolume = 0.8f;

        public float SfxVolume => _sfxVolume;

        public void OnUpgrade(int fromVersion)
        {
            if (fromVersion < 2)
            {
                _sfxVolume = _musicVolume;
            }
        }
    }
}
On This Page