Here's a robust save system for Godot 4.2 using C# that saves to a .json file using Newtonsoft.Json, and includes a failsafe mechanism to recover from a corrupted main save file by falling back to the previous backup.
✅ Features
- Serializes game state to JSON using
Newtonsoft.Json.
- Saves to a main file (
save.json) and creates a backup (save_backup.json).
- On save:
- Writes to a temporary file.
- Renames the current main save to backup.
- Renames the temporary file to become the new main save.
- On load:
- Tries to load from the main file.
- If the main file is corrupted or missing, tries the backup.
- Safe file operations using Godot's
FileAccess and DirAccess.
📁 File Paths
| File Type | Path |
|---|
| Main Save | user://save.json |
| Backup Save | user://save_backup.json |
| Temporary Save | user://save_temp.json |
📄 SaveSystem.cs (C# Script)
using Godot;
using Newtonsoft.Json;
using System;
public static class SaveSystem
{
private const string MainSavePath = "save.json";
private const string BackupSavePath = "save_backup.json";
private const string TempSavePath = "save_temp.json";
private const string UserDir = "user://";
/// <summary>
/// Saves the provided SaveData to a JSON file, with a backup.
/// </summary>
public static void Save(SaveData data)
{
try
{
// Serialize the data to JSON
string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
// Write to temporary file
using (var file = FileAccess.Open(UserDir + TempSavePath, FileAccess.ModeFlags.Write))
{
file.StoreString(jsonData);
}
// Open user directory
DirAccess dir = DirAccess.Open(UserDir);
if (dir == null)
{
throw new Exception("Could not open user directory.");
}
// If main save exists, move it to backup
if (dir.FileExists(MainSavePath))
{
if (dir.FileExists(BackupSavePath))
{
dir.Remove(BackupSavePath); // Delete old backup
}
dir.Move(MainSavePath, BackupSavePath); // Rename main to backup
}
// Move temp to main
dir.Move(TempSavePath, MainSavePath);
}
catch (Exception ex)
{
GD.PrintErr($"Failed to save game: {ex.Message}\n{ex.StackTrace}");
CleanupTempFile();
}
}
/// <summary>
/// Loads the most recent save data from either main or backup.
/// </summary>
public static SaveData Load()
{
SaveData result = null;
// Try loading from main save
try
{
if (FileAccess.FileExists(UserDir + MainSavePath))
{
using (var file = FileAccess.Open(UserDir + MainSavePath, FileAccess.ModeFlags.Read))
{
string json = file.GetAsText();
result = JsonConvert.DeserializeObject<SaveData>(json);
}
return result;
}
}
catch (Exception ex)
{
GD.PrintErr($"Failed to load main save: {ex.Message}");
}
// If main failed, try backup
try
{
if (FileAccess.FileExists(UserDir + BackupSavePath))
{
using (var file = FileAccess.Open(UserDir + BackupSavePath, FileAccess.ModeFlags.Read))
{
string json = file.GetAsText();
result = JsonConvert.DeserializeObject<SaveData>(json);
}
return result;
}
}
catch (Exception ex)
{
GD.PrintErr($"Failed to load backup save: {ex.Message}");
}
return null; // No valid save found
}
private static void CleanupTempFile()
{
DirAccess dir = DirAccess.Open(UserDir);
if (dir != null && dir.FileExists(TempSavePath))
{
dir.Remove(TempSavePath);
}
}
/// <summary>
/// Example SaveData class. Replace this with your actual game state.
/// </summary>
public class SaveData
{
public int PlayerScore { get; set; }
public Vector2 PlayerPosition { get; set; }
public string CurrentLevel { get; set; }
}
}
🧪 Usage Example
Saving Game State
SaveSystem.SaveData data = new SaveSystem.SaveData
{
PlayerScore = 100,
PlayerPosition = new Vector2(100, 200),
CurrentLevel = "Level1"
};
SaveSystem.Save(data);
Loading Game State
SaveSystem.SaveData loadedData = SaveSystem.Load();
if (loadedData != null)
{
GD.Print($"Loaded score: {loadedData.PlayerScore}");
}
else
{
GD.Print("No save data found.");
}
🛡️ Notes
- Ensure Newtonsoft.Json is installed via NuGet or included in your project.
- The
SaveData class is an example — replace it with your actual game state class.
- This system ensures that even if the main save file becomes corrupted, the user can fall back to the last known good state automatically.
- All file operations are done using Godot's
FileAccess and DirAccess for cross-platform compatibility.
📌 Optional Enhancements
- Add UI for manual backup restoration.
- Add a confirmation dialog if both main and backup fail to load.
- Log save/load timestamps or versions for debugging.
This implementation provides a clean, robust, and failsafe save system tailored for Godot 4.2 using C#.