A file-based save system lets your game remember player progress by saving data to a file on the device. This way, players can continue where they left off even after closing the game.
File-based save system in Unity
using System.IO; using UnityEngine; public class SaveSystem { private string filePath = Application.persistentDataPath + "/savefile.json"; public void Save(string data) { File.WriteAllText(filePath, data); } public string Load() { if (File.Exists(filePath)) { return File.ReadAllText(filePath); } return null; } }
Use Application.persistentDataPath to get a safe place to save files on any device.
Use File.WriteAllText to save text data and File.ReadAllText to load it back.
File.WriteAllText(filePath, "Hello World");
string content = File.ReadAllText(filePath);string path = Application.persistentDataPath + "/playerdata.json"; if (File.Exists(path)) { string json = File.ReadAllText(path); }
This program saves a player's level and health to a JSON file and then loads it back, printing the values to the Unity console.
using System.IO; using UnityEngine; [System.Serializable] public class PlayerData { public int level; public float health; } public class SaveSystemExample : MonoBehaviour { private string filePath; void Start() { filePath = Application.persistentDataPath + "/playerdata.json"; // Create some data PlayerData data = new PlayerData { level = 5, health = 75.5f }; // Convert to JSON string json = JsonUtility.ToJson(data); // Save to file File.WriteAllText(filePath, json); // Load from file if (File.Exists(filePath)) { string loadedJson = File.ReadAllText(filePath); PlayerData loadedData = JsonUtility.FromJson<PlayerData>(loadedJson); Debug.Log($"Loaded Level: {loadedData.level}, Health: {loadedData.health}"); } } }
Always check if the file exists before loading to avoid errors.
Use JSON format to save complex data like player stats in a readable way.
Files saved in Application.persistentDataPath stay between game sessions and app updates.
A file-based save system stores game data on the device so progress is not lost.
Use File.WriteAllText and File.ReadAllText with Application.persistentDataPath for safe saving and loading.
JSON is a simple format to save and load structured data like player stats.