In this lesson, you will learn how to implement an automated multi-file backup system to ensure player progress remains intact even if a save operation is interrupted by a crash or disk error.
The Strategy: The "Three-Generation" Rotation
Writing directly to your active save file is risky; if the application crashes mid-write, you risk corrupting the only copy of the player's data. To solve this, we implement a backup mechanism that maintains a rotation of files: the Primary, the Backup, and the Temporary file.
Instead of overwriting the main file immediately, use this three-step workflow:
- Write to Temporary: Serialize your data to a
.tmpfile. This prevents the primary file from being modified until the data is fully written. - Rotate Backups: If the write is successful, rename the current
save.dattosave.bak. - Commit: Rename your
save.tmptosave.dat.
Implementation Logic
Using System.IO.File, you can manage these transitions safely. If an exception occurs during the "write to temporary" phase, your original save.dat remains untouched.
public void SaveGame(string data) {
string path = Path.Combine(Application.persistentDataPath, "save.dat");
string backupPath = Path.Combine(Application.persistentDataPath, "save.bak");
string tempPath = Path.Combine(Application.persistentDataPath, "save.tmp");
try {
File.WriteAllText(tempPath, data); // 1. Write to temp
if (File.Exists(path)) {
File.Replace(tempPath, path, backupPath); // 2 & 3. Atomically replace
} else {
File.Move(tempPath, path);
}
} catch (IOException e) {
Debug.LogError($"Save failed: {e.Message}. Original data preserved.");
}
}
Recovery
On game startup, your SaveManager should perform a health check. If save.dat is inaccessible or fails a checksum validation, the system should automatically attempt to load save.bak. This "fail-safe" ensures that the player only loses the most recent session's progress rather than their entire career. Always ensure you verify the integrity of the backup before overwriting the primary file during a recovery operation.
Key Takeaway: Never overwrite your master save file directly; write to a temporary file first and use atomic file operations to rotate backups, ensuring you always have a fallback if the write process is interrupted.