TExcelTAD
Home › Unity with C# › Save & Load: JSON and PlayerPrefs

Save & Load: JSON and PlayerPrefs

Unity has no built-in "save game" system. You decide what to save, serialize it, and write it somewhere. This lesson covers the two built-in tools (PlayerPrefs and JsonUtility), where files should go, and the habits that keep old save files loading after updates.

PlayerPrefs: settings only

PlayerPrefs stores small key/value pairs (int, float, string):

csharp
PlayerPrefs.SetFloat("musicVolume", 0.8f);
PlayerPrefs.SetInt("invertY", 1);
PlayerPrefs.Save();                                   // also saved automatically on a clean quit
float volume = PlayerPrefs.GetFloat("musicVolume", 1f);   // default when missing

Its limits make it wrong for save games:

  • It's stored in the Windows registry, a macOS .plist, Android SharedPreferences, or browser storage on the web. Not a file you can back up, sync to the cloud or offer as save slots.
  • No structure: you'd invent keys like slot2_inventory_item7_count.
  • It's plain text that players can edit, and it has size limits on some platforms (the Web build has a small quota).

Use it for settings, rebinding overrides and "last selected slot". Use files for saves.

JSON files

csharp
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

[Serializable]
public class SaveData
{
    public int version = 2;
    public string sceneName;
    public Vector3 playerPosition;          // JsonUtility handles Unity structs
    public int coins;
    public List<string> collectedIds = new();
}

public static class SaveSystem
{
    static string PathFor(int slot) => Path.Combine(Application.persistentDataPath, 
quot;save{slot}.json"); public static void Save(SaveData data, int slot) { string json = JsonUtility.ToJson(data, prettyPrint: true); string path = PathFor(slot), temp = path + ".tmp"; File.WriteAllText(temp, json); // write to a temp file first... if (File.Exists(path)) File.Replace(temp, path, path + ".bak"); else File.Move(temp, path); // ...then swap, so a crash never leaves half a file } public static SaveData Load(int slot) { string path = PathFor(slot); if (!File.Exists(path)) return null; return JsonUtility.FromJson<SaveData>(File.ReadAllText(path)); } }

Application.persistentDataPath is a per-user, writable folder that survives updates (for example under AppData/LocalLow/<company>/<product> on Windows). Never write into Application.dataPath or StreamingAssets; they are read-only in builds.

JsonUtility is fast and allocation-light but limited: it serializes public fields and [SerializeField] fields of [Serializable] types, not properties, dictionaries, top-level arrays, or polymorphic types. When you need those, add the Newtonsoft Json package (com.unity.nuget.newtonsoft-json) and use JsonConvert.

What to save: ids, not objects

Save data, not GameObjects or asset references. A saved Coin reference is meaningless next session. Give every collectible, door and definition a stable string id ("coin_cave_03"), save the ids, and rebuild the world from them on load.

Versions and migration

Your game will change after release. Every save should carry a version, and loading should upgrade older formats step by step. The model below does that with System.Text.Json (the same idea works with JsonUtility or Newtonsoft):

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Nodes;

// A v1 save from launch day: "gold" was later renamed to "coins", and v3 added "collected".
string fromDisk = """{"version":1,"scene":"Cave","gold":120}""";

var data = SaveSystem.Load(fromDisk);
Console.WriteLine(
quot;loaded: scene={data.Scene} coins={data.Coins} collected=[{string.Join(", ", data.Collected)}] version={data.Version}"); data.Collected.Add("coin_cave_03"); data.Coins += 5; string written = SaveSystem.Save(data); Console.WriteLine(
quot;saved: {written}"); Console.WriteLine(
quot;round trip equal: {SaveSystem.Save(SaveSystem.Load(written)) == written}"); class SaveData { public int Version { get; set; } = SaveSystem.CurrentVersion; public string Scene { get; set; } = "Start"; public int Coins { get; set; } public List<string> Collected { get; set; } = new(); } static class SaveSystem { public const int CurrentVersion = 3; static readonly JsonSerializerOptions Options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; public static string Save(SaveData d) => JsonSerializer.Serialize(d, Options); public static SaveData Load(string json) { var node = JsonNode.Parse(json)!.AsObject(); int version = node["version"]!.GetValue<int>(); while (version < CurrentVersion) { Console.WriteLine(
quot; migrating v{version} -> v{version + 1}"); if (version == 1) { node["coins"] = node["gold"]!.GetValue<int>(); node.Remove("gold"); } if (version == 2) { node["collected"] = new JsonArray(); } version++; node["version"] = version; } return node.Deserialize<SaveData>(Options)!; } }
  migrating v1 -> v2
  migrating v2 -> v3
loaded: scene=Cave coins=120 collected=[] version=3
saved:  {"version":3,"scene":"Cave","coins":125,"collected":["coin_cave_03"]}
round trip equal: True

Keep every migration step forever, and keep a few real save files from each release as test fixtures. A failing old save is a one-star review.

Practical checklist

  1. Save on meaningful events (checkpoint, level end, quitting) and in OnApplicationPause(true) on mobile, where apps are killed without warning.
  2. Write to a temp file and swap (above). Keep one backup.
  3. Treat loaded data as untrusted: clamp values, ignore unknown ids, never crash on a bad file; offer to start fresh.
  4. Anti-cheat for single-player saves is rarely worth it. For competitive or paid content, validate on a server instead of encrypting local files.

Test yourself

Which is a good use of PlayerPrefs?

  1. A full save game with inventory
  2. The music volume setting
  3. A 5 MB level layout
  4. Multiplayer state

What can JsonUtility NOT serialize?

  1. A public int field
  2. A List<string> field
  3. A Dictionary<string, int> field
  4. A Vector3 field

Why write the save to a temporary file and then replace the real one?

  1. It's faster
  2. A crash or power loss mid-write can't leave a corrupted save
  3. JsonUtility requires it
  4. To hide the file from players