Saving progress
Assets/
Scenes/
Arena.unity
Scripts/
you already havethis lesson adds
A mobile game gets interrupted constantly: a phone call, a notification, the OS killing the app to free memory. If closing the app loses progress, nobody comes back.
Turn a plain C# class into JSON, write it to persistentDataPath, read it back on launch.
PlayerPrefs or a file?
✓ PlayerPrefs
✓ JSON file
Step 1 — a plain data class
The save class holds values, never MonoBehaviours. You cannot serialise a GameObject — write down what you need to rebuild it instead.
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class SaveData
{
public int version = 1; // bump this when the shape changes
public int level = 1;
public float health = 100f;
public int gold;
public float playTimeSeconds;
public string sceneName = "Arena";
public Vector3 playerPosition; // Unity serialises Vector3 fine
public List<string> ownedArtifacts = new List<string>();
public List<string> equippedArtifacts = new List<string>();
public string savedAtUtc = "";
}Step 2 — write and read it
using System;
using System.IO;
using UnityEngine;
public static class SaveSystem
{
// the ONLY folder you are allowed to write to on iOS and Android
private static string Path => System.IO.Path.Combine(Application.persistentDataPath, "save.json");
public static bool Exists => File.Exists(Path);
public static void Save(SaveData data)
{
data.savedAtUtc = DateTime.UtcNow.ToString("o");
string json = JsonUtility.ToJson(data, prettyPrint: true);
string temp = Path + ".tmp";
// if the phone dies mid-write, the old save is still intact
File.WriteAllText(temp, json);
File.Copy(temp, Path, overwrite: true);
File.Delete(temp);
Debug.Log("Saved to " + Path);
}
public static SaveData Load()
{
if (!Exists) return new SaveData(); // first run
try
{
string json = File.ReadAllText(Path);
SaveData data = JsonUtility.FromJson<SaveData>(json);
return Migrate(data);
}
catch (Exception e)
{
// a corrupt save must never brick the game
Debug.LogError("Save file unreadable, starting fresh: " + e.Message);
File.Move(Path, Path + ".broken");
return new SaveData();
}
}
public static void Delete()
{
if (Exists) File.Delete(Path);
}
/// old saves must keep working after you ship an update
private static SaveData Migrate(SaveData data)
{
if (data.version < 1)
{
data.gold = 0;
data.version = 1;
}
return data;
}
}Application.persistentDataPath is the only writable folder on a phone. Application.dataPath is read-only inside the app bundle.
The temp-file swap protects against a half-written save when the OS kills the app mid-write.
Always wrap Load in try/catch. A user with a corrupt file who cannot open the game will leave a one-star review.
The version field costs nothing today and saves you the day you add a field in update 1.3.
Step 3 — save at the right moments
Do not save every frame, and do not only save when the player taps a button — on a phone they will never get the chance.
using UnityEngine;
public class GameSession : MonoBehaviour
{
public static GameSession Instance { get; private set; }
public SaveData Data { get; private set; }
[SerializeField] private CharacterStats playerStats; // the Knight's
[SerializeField] private Transform player;
void Awake()
{
if (Instance != null) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
Data = SaveSystem.Load();
Apply(Data);
}
void Update() => Data.playTimeSeconds += Time.deltaTime;
void Collect()
{
Data.health = playerStats.currentHealth;
Data.playerPosition = player.position;
Data.sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
}
void Apply(SaveData d)
{
playerStats.currentHealth = d.health;
if (d.playerPosition != Vector3.zero) player.position = d.playerPosition;
}
/// fires when the app goes to the background — THIS is the important one on mobile
void OnApplicationPause(bool paused)
{
if (paused) { Collect(); SaveSystem.Save(Data); }
}
/// desktop and a graceful exit
void OnApplicationQuit()
{
Collect();
SaveSystem.Save(Data);
}
}Checkpoints, not autosave spam
Save when the player enters a new area, finishes a fight, buys something, or the app backgrounds.
Writing a small JSON file takes about a millisecond. Writing it 60 times a second still wears the flash storage.
Show a tiny 'saved' indicator for half a second. Players distrust games that save invisibly.
Finding the file to debug it
# print the path from inside the game
Debug.Log(Application.persistentDataPath);
# Android — pull the save off the device
adb shell run-as com.yourstudio.yourgame cat files/save.json
# Editor paths
# macOS ~/Library/Application Support/CompanyName/ProductName/
# Windows %USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\