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, andstring, 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 soJsonUtilitycan convert it to and from JSON text.Application.persistentDataPathis a writable, platform-correct folder that survives app updates and reinstalls (unlikeApplication.dataPath, which lives inside the read-only app install).JsonUtilityonly serializes public fields (not properties orDictionarys), keep save data structures simple for it to work smoothly.