Patch 1.3 arrives with a small improvement. During development, someone on the team noticed that the inventory field gold had been called that since the prototype. Since the game now had three different currencies, they renamed it to coins. The tests passed. QA tried new games and everything worked. The patch shipped on a Friday, and by Monday there were hundreds of negative reviews from players who had loaded their save and found themselves without a single coin.
It wasn't a serializer bug. It did exactly what it had been programmed to do: read the file, find no coins field and therefore leave the default value: zero. No error, no exception, no log. The gold field was still in the file, with the player's 48,000 coins, but it was no longer being read.
A save system is not a feature you build at the end of the project, which is a mistake everyone makes when starting out. It is a data format that has to keep working for the entire life of the game, and that every patch is going to break by accident.
1. Decide what gets saved and what gets rebuilt
The first mistake of many save systems is trying to save the game state exactly as it sits in memory.
In Unity, that usually means serializing MonoBehaviours. In Unreal, saving whole actors. It works in the prototype. But the file format ends up tied to the internal structure of the classes, and it becomes a problem as soon as the code changes.
To avoid it, ask yourself: what is the minimum state from which I can rebuild everything else? It is almost always much less than it seems:
- Saved: What the player has decided or achieved: inventory, quest progress, stats, position on the map, story flags, settings...
- Rebuilt: What can be derived: final stats (from level and gear), visual state, enemy AI, references between objects...
It is also important to always save by identifier, never by reference. An inventory item is saved as "sword_iron", not as a reference to a ScriptableObject or an asset. The id survives the asset being moved or renamed; the reference does not.
As a rule of thumb, if the save file contains class names, asset paths or internal engine GUIDs, it is saving the implementation, not the game state.
But separating the save model from the game model comes at a cost: you need a conversion step in each direction. That is exactly where migrations live, and without it there is no clean way to evolve the format.
2. JSON vs binary
The next decision is the format. The two main reasonable options both have clear advantages:
- JSON (or any text format with field names). It is readable, can be inspected and edited by hand during development, tolerates new or missing fields, and makes migrations much easier because you can manipulate the document before converting it into objects. On the downside, it usually takes more space and is slower to process.
- Binary. It is compact and fast. But if the format depends on field order, any change in the structure shifts everything that comes after it, and the old file is no longer usable.
For most games, save file size is not a bottleneck, and the flexibility of a format with field names more than makes up for it. In cases like consoles with strict quotas or cloud saves, where file size does matter, you can compress the JSON, which shrinks it a lot without losing its advantages.
In Unity, JsonUtility falls short quickly: it doesn't serialize dictionaries or properties, among other things. The usual alternative is Newtonsoft Json, available as an official package (com.unity.nuget.newtonsoft-json), which also lets you work with the document as a tree (JObject), and that is what you need for migrating.
In Unreal, the standard path is a USaveGame subclass with UPROPERTY() properties. Serialization is binary, but it is tagged: each property is saved with its name and type, so adding new properties or removing old ones doesn't break reading. Renaming a property or changing its type does.
3. Version the format from day one
Every save file should carry a version number from the first build that reaches a player. It is one line of code, and adding it later is much harder: you have to somehow tell apart the files that don't have it from the ones that do, and handle them differently.
The idea is simple: every time the format changes in an incompatible way, the version is incremented and you write a migration that transforms a file from version n to version n + 1. On load, all migrations from the file's version up to the current one are applied in sequence.
1using Newtonsoft.Json.Linq;
2
3public interface ISaveMigration
4{
5 int FromVersion { get; }
6 void Apply(JObject save);
7}
8
9public static class SaveMigrator
10{
11 public const int CurrentVersion = 3;
12
13 private static readonly ISaveMigration[] Migrations =
14 {
15 new V1_AddSettings(), // 1 -> 2
16 new V2_RenameGoldToCoins(), // 2 -> 3
17 };
18
19 public static JObject Migrate(JObject save)
20 {
21 int version = save.Value<int?>("version") ?? 1;
22
23 if (version > CurrentVersion)
24 throw new SaveTooNewException(version);
25
26 foreach (var migration in Migrations)
27 {
28 if (migration.FromVersion < version) continue;
29 migration.Apply(save);
30 version = migration.FromVersion + 1;
31 save["version"] = version;
32 }
33
34 return save;
35 }
36}Migrations are small, and each one only knows about two consecutive versions. The one from the opening example would look like this:
1public class V2_RenameGoldToCoins : ISaveMigration
2{
3 public int FromVersion => 2;
4
5 public void Apply(JObject save)
6 {
7 var inventory = (JObject)save["inventory"];
8 if (inventory?["gold"] is JToken gold)
9 {
10 inventory["coins"] = gold;
11 inventory.Remove("gold");
12 }
13 }
14}This way, every new update keeps working with older files, applying a change that adapts all the old data to the new content.
Unreal has a more elaborate native mechanism called custom versions (FCustomVersionRegistration and Ar.CustomVer inside Serialize), which is what the engine itself uses to version its formats. For a simple USaveGame, a SaveVersion field and a migration function after LoadGameFromSlot is easier to read and test, and covers most cases.
There is one case no migration can solve: a file with a newer version than the game, which is the SaveTooNewException in the example. This usually happens when a player syncs saves through the cloud between two devices running different versions of the game, or when they try a beta or PTS with upcoming improvements and then go back to the stable version.
In those cases you have to refuse to load, with a clear message, and above all not overwrite the file: the older version of the game doesn't know what it contains, and saving over it would destroy the progress.
4. Some rules for migrations
These are some of the recommendations I can offer after maintaining a save format across several patches:
- Migrations are never deleted. A player can come back to the game after two years with a version 1 save. The whole chain has to keep working. This is usually the easiest one to forget: a developer who has been updating a game for 10 years never thinks there might be players coming back after 5 years of inactivity.
- A migration does not use the game's current classes. It works on the document (the
JObject, or the raw fields), not on the code's types. If migration 2 uses theInventoryclass and that class changes in version 7, migration 2 stops compiling or, worse, changes behavior. - Removed identifiers need a destination. If an item disappears from the game, the old file will still have it. The migration must decide what to do: replace it with something else, convert it into currency or remove it. What cannot happen is the game crashing when loading an identifier that no longer exists, or referencing objects that stopped working in the game a long time ago.
- Every released version leaves a test file behind. Before releasing, a real save from that version is stored in the repository. The load tests take all those files, migrate them to the current version and check that they load without errors and with the expected values.
1[TestCase("saves/v1_early_game.json")]
2[TestCase("saves/v2_mid_game.json")]
3[TestCase("saves/v3_endgame_100h.json")]
4public void OldSavesLoadIntoCurrentVersion(string path)
5{
6 var json = JObject.Parse(File.ReadAllText(path));
7 var migrated = SaveMigrator.Migrate(json);
8
9 Assert.AreEqual(SaveMigrator.CurrentVersion, migrated.Value<int>("version"));
10 Assert.DoesNotThrow(() => SaveData.FromJson(migrated));
11}Every save file is a contract with a player. The code can change as much as it wants, as long as the contract keeps being honored.
5. Each system saves its own part
As the game grows, a single SaveData with everything inside ends up being a bottleneck. Inventory, quests, settings and achievements all touch the same class, and any change in one of them forces you to bump the version of the whole file and write a migration that walks through data it doesn't care about. On top of that, for the developer, changing one value means going through the full data tree and other structures they have no interest in.
What scales better is for each system to own its own section of the file, identified by a fixed key and with its own version. The save manager doesn't know what is inside each section: it goes through the registered systems, asks them for their data and stores it under their key. On load it does the opposite, and each system migrates its section starting from the version it was saved with.
1public interface ISaveable
2{
3 string SaveKey { get; } // "inventory", "quests"... never changes
4 int SaveVersion { get; }
5 JObject Capture();
6 void Restore(JObject data, int fromVersion);
7}
8
9public class SaveManager
10{
11 private readonly List<ISaveable> saveables = new();
12
13 public void Register(ISaveable saveable) => saveables.Add(saveable);
14
15 public JObject CaptureAll()
16 {
17 var sections = new JObject();
18 foreach (var s in saveables)
19 {
20 sections[s.SaveKey] = new JObject
21 {
22 ["version"] = s.SaveVersion,
23 ["data"] = s.Capture(),
24 };
25 }
26
27 return new JObject
28 {
29 ["version"] = SaveMigrator.CurrentVersion,
30 ["sections"] = sections,
31 };
32 }
33
34 public void RestoreAll(JObject save)
35 {
36 var sections = (JObject)save["sections"];
37 foreach (var s in saveables)
38 {
39 // A new system has no section in old saves: it keeps its default values.
40 if (sections?[s.SaveKey] is not JObject section) continue;
41 s.Restore((JObject)section["data"], section.Value<int>("version"));
42 }
43 }
44}In Unreal, the usual approach is to mark properties with UPROPERTY(SaveGame) and serialize the object with ArIsSaveGame. It uses the same tagged serialization as USaveGame, so it handles new or removed properties just as well.
The global file version doesn't go away: it is still used for changes to the structure of the file itself, such as moving from a single block to sections. But the day-to-day work of each system no longer touches it.
Each section's key is part of the format. Renaming "inventory" to "bag" is exactly the same mistake as renaming gold to coins: the old section is still in the file, but nobody reads it.
6. Writing without corrupting
The second big cause of lost saves isn't patches, it's writing. If the game is writing the file and at that moment the power goes out, the console goes to sleep, the player kills the process or the OS kills the app on mobile, the file is left half-written. Half a JSON can't be parsed, and the whole save is gone.
The solution is to never write directly over the good file. You first write to a temporary file, make sure the data has reached the disk, and only then replace the original file with the new one, in an operation the file system performs atomically:
1public static void WriteAtomic(string path, string contents)
2{
3 string temp = path + ".tmp";
4 string backup = path + ".bak";
5
6 using (var stream = new FileStream(temp, FileMode.Create, FileAccess.Write))
7 using (var writer = new StreamWriter(stream))
8 {
9 writer.Write(contents);
10 writer.Flush();
11 stream.Flush(flushToDisk: true);
12 }
13
14 if (File.Exists(path))
15 File.Replace(temp, path, backup); // replaces and keeps the previous version
16 else
17 File.Move(temp, path);
18}The .bak file is the safety net. On load, if the main file can't be read (or fails validation), the previous copy is tried instead. The player loses a few minutes of progress instead of eighty hours.
On consoles and some mobile platforms, disk access goes through the platform's save APIs, which have their own rules (maximum sizes, transactional operations, mandatory "don't turn off your console" notices). In Unreal, UGameplayStatics::SaveGameToSlot already relies on each platform's save system. The temp file plus backup pattern is still valid on PC, but on console you have to follow whatever the platform requires.
But to know when to fall back to the copy, you first have to detect that the main file is broken.
7. Validating what gets loaded
A half-written file doesn't always fail when parsed. If the JSON gets cut at just the right point, it can be syntactically valid but incomplete, and a binary file can be read without errors even though it contains garbage values. The reliable way to detect this is to use a hash of the content, written alongside the data. On load it is computed again, and if it doesn't match, the file is not used and the game falls back to the last saved backup.
1// On-disk format: first line, the hash; the rest, the JSON.
2public static string WithChecksum(string json) => Hash(json) + "\n" + json;
3
4public static JObject Load(string path)
5{
6 // Main file first; if it is damaged, the copy of the last good save.
7 return TryRead(path) ?? TryRead(path + ".bak")
8 ?? throw new SaveCorruptedException(path);
9}
10
11private static JObject TryRead(string path)
12{
13 if (!File.Exists(path)) return null;
14
15 string[] parts = File.ReadAllText(path).Split('\n', 2);
16 if (parts.Length < 2 || parts[0] != Hash(parts[1]))
17 return null;
18
19 return JObject.Parse(parts[1]);
20}
21
22private static string Hash(string text)
23{
24 using var sha = SHA256.Create();
25 byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(text));
26 return BitConverter.ToString(bytes).Replace("-", "");
27}To detect accidental corruption, a CRC32 is enough (a 32-bit check code, very fast to compute, designed to catch accidental errors rather than tampering). Against a player trying to edit the file, no hash stored alongside the data is much use, since whoever edits it can recompute the hash too. In cases where this matters (leaderboards, competitive games, multiplayer data...), validation has to happen on a server to guarantee that security.
The checksum tells you the file is the one that was written, not that its contents make sense. A bug from three patches ago may have saved negative coins, a level above the cap or an item that no longer exists. That is why, whenever a migration runs and before handing the data to the game, it is worth doing one last sanitizing pass that fixes the impossible and leaves a record of it:
1public static void Sanitize(SaveData save, ItemDatabase items)
2{
3 save.Coins = Mathf.Max(0, save.Coins);
4 save.Level = Mathf.Clamp(save.Level, 1, MaxLevel);
5
6 int removed = save.Inventory.RemoveAll(id => !items.Exists(id));
7 if (removed > 0)
8 Debug.LogWarning($"Removed {removed} unknown items from the save");
9}It is better for the player to load a save with one item missing than a corrupted one that won't let them play.
The log lets you find out later where the broken data came from.
8. Saving without hitches
The last problem is performance. Serializing a large save and writing it to disk can take tens of milliseconds (it sounds like little, but you feel it while playing), and if it happens on the main thread during an autosave, the player perceives it as a hitch. As I mentioned in the Unity profiling article, these one-off spikes are among the most annoying, because they don't show up in the average FPS and they are hard to track down.
The solution has two parts.
- On the main thread, only do what is essential: copy the game state into the save model. This is what is known as a snapshot: a flat, fast copy of the data, both to create and to read.
- In the background, serialization to text and writing to disk happen on that snapshot, which no longer changes even though the game keeps running.
1public async Task SaveAsync()
2{
3 // Main thread: copy the state, nothing else.
4 SaveData snapshot = SaveData.CaptureFrom(gameState);
5
6 // Background: serialize and write.
7 await Task.Run(() =>
8 {
9 string json = JsonConvert.SerializeObject(snapshot);
10 WriteAtomic(savePath, json);
11 });
12}In Unreal, UGameplayStatics::AsyncSaveGameToSlot does the writing in the background and notifies you through a delegate when it is done. Copying the state into the USaveGame is still the responsibility of the game and the developer, and it should also be a plain data copy, not an expensive walk through the world.
Whenever possible, avoid two saves overlapping. If the autosave fires while the previous one is still writing, both compete for the same temporary file. A single-slot queue (if a save is in progress, the next one waits and only the most recent is kept) can be a good solution.
9. What I would have in place before the first public build
A save system doesn't have to be complex, but it does have to be thought through before the first player saves their first game. This is the minimum I would have ready:
- A save model separate from the game model, with identifiers instead of references.
- A version field in the file from day one, and an empty migrator ready for the first migration.
- One section per system, with a fixed key and its own version.
- Atomic writes with a backup copy, and a load that tries the copy if the main file fails.
- A checksum on save and sanitizing on load, so corrupted or impossible data is never taken as valid.
- Two-phase saving: snapshot on the main thread, serialization and writing in the background.
- A test file for every released version in the repository, loaded by the tests on every build.
None of these pieces takes more than an afternoon. The expensive part is finding out they were needed after a patch has wiped players' progress, because those saves can no longer be recovered.



