Unity Essentials: Physics, UI & Gameplay Systems

Lesson 7 of 8

Saving and Loading Data

Progress needs to survive closing the game. Unity gives you a couple of straightforward options depending on how much data you're saving.

using UnityEngine;

// Small values: PlayerPrefs
PlayerPrefs.SetInt("HighScore", 4200);
PlayerPrefs.SetFloat("MusicVolume", 0.8f);
PlayerPrefs.Save();

int highScore = PlayerPrefs.GetInt("HighScore", 0); // 0 is the default if missing

PlayerPrefs

  • A simple key-value store, backed by the registry on Windows or a plist on Mac, good for small things like settings or a high score.
  • Only stores int, float, and string, and isn't encrypted, don't use it for anything you can't afford a player to see or tamper with.

Larger or structured data: JSON

using System.IO;
using UnityEngine;

[System.Serializable]
public class SaveData
{
    public int level;
    public int[] unlockedItems;
}

void Save(SaveData data)
{
    string json = JsonUtility.ToJson(data);
    File.WriteAllText(Application.persistentDataPath + "/save.json", json);
}

SaveData Load()
{
    string path = Application.persistentDataPath + "/save.json";
    if (!File.Exists(path)) return new SaveData();
    return JsonUtility.FromJson<SaveData>(File.ReadAllText(path));
}

The pieces

  • [System.Serializable] marks a plain class so JsonUtility can convert it to and from JSON text.
  • Application.persistentDataPath is a writable, platform-correct folder that survives app updates and reinstalls (unlike Application.dataPath, which lives inside the read-only app install).
  • JsonUtility only serializes public fields (not properties or Dictionarys), keep save data structures simple for it to work smoothly.

📝 Save Data Quiz

Passing score: 70%
  1. 1.Which types can PlayerPrefs store directly?

  2. 2.Application.____ is the writable, platform-correct folder for save files that survives app updates.

  3. 3.PlayerPrefs data is encrypted by default, making it safe to store sensitive values.