Bird
Raised Fist0
Unityframework~10 mins

File-based save system in Unity - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - File-based save system
Start Save Request
↓
Gather Data to Save
↓
Convert Data to String
↓
Open/Create File
↓
Write Data to File
↓
Close File
↓
Save Complete
↓
Start Load Request
↓
Open File
↓
Read Data from File
↓
Convert String to Data
↓
Apply Loaded Data
↓
Load Complete
This flow shows how a game saves data by converting it to a string and writing it to a file, then later reads the file and converts the string back to data.
Execution Sample
Unity
using System.IO;

void SaveScore(int score) {
  string path = "savefile.txt";
  File.WriteAllText(path, score.ToString());
}

int LoadScore() {
  string path = "savefile.txt";
  return int.Parse(File.ReadAllText(path));
}
This code saves an integer score to a text file and loads it back by reading the file and converting the text to an integer.
Execution Table
StepActionData/VariableFile ContentResult/Output
1Call SaveScore(42)score=42Start saving
2Convert score to stringscoreStr="42"Ready to write
3Write string to filescoreStr="42"File contains: "42"Data saved
4Close fileFile contains: "42"Save complete
5Call LoadScore()File contains: "42"Start loading
6Read string from fileFile contains: "42"Read "42"
7Convert string to intloadedScore=42File contains: "42"Data loaded
8Return loadedScoreloadedScore=42File contains: "42"Load complete, returns 42
💡 Execution stops after saving and loading complete successfully.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 7Final
scoreundefined42424242
scoreStrundefined"42""42""42""42"
loadedScoreundefinedundefinedundefined4242
File Content"""""42""42""42"
Key Moments - 3 Insights
Why do we convert the score to a string before saving?
Files store text, so we convert numbers to strings to save them. See execution_table step 2 where score 42 becomes "42".
What happens if the file does not exist when loading?
Reading a non-existent file causes an error. The code assumes the file exists (execution_table step 6). In real use, check file existence before reading.
Why do we parse the string back to int when loading?
Data read from files is text. To use it as a number, we convert it back. See execution_table step 7 where "42" becomes 42.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the file content after step 3?
A"int.Parse(42)"
B"score=42"
C"42"
D""
💡 Hint
Check the 'File Content' column at step 3 in execution_table.
At which step does the program convert the loaded string back to an integer?
AStep 7
BStep 5
CStep 6
DStep 8
💡 Hint
Look for 'Convert string to int' action in execution_table.
If we change SaveScore to save "score:42" instead of "42", what changes in the execution_table?
ANo change in file content
BFile content at step 3 becomes "score:42"
CLoaded score at step 7 becomes "score:42"
DProgram crashes at step 2
💡 Hint
Focus on the 'File Content' column at step 3 and how SaveScore writes data.
Concept Snapshot
File-based save system in Unity:
- Convert data to string (e.g., score.ToString())
- Use File.WriteAllText(path, data) to save
- Use File.ReadAllText(path) to load
- Convert loaded string back to data type (e.g., int.Parse)
- Always handle file existence and errors in real projects
Full Transcript
This visual execution shows how a file-based save system works in Unity. First, the program converts the data (like a score) to a string because files store text. Then it writes this string to a file. Later, when loading, it reads the string from the file and converts it back to the original data type. The execution table traces each step, showing variable values and file content. Key moments explain why conversion is needed and what happens if the file is missing. The quiz tests understanding of these steps. This method helps games remember player progress between sessions.

Practice

(1/5)
1. What is the main purpose of using a file-based save system in Unity games?
easy
A. To store game data on the device so progress is not lost
B. To improve game graphics performance
C. To increase the game's frame rate
D. To connect the game to online multiplayer servers

Solution

  1. Step 1: Understand the role of saving data

    Saving data means keeping player progress or settings so they are not lost when the game closes.
  2. Step 2: Identify file-based save system purpose

    A file-based save system stores this data on the device's storage, allowing the game to load it later.
  3. Final Answer:

    To store game data on the device so progress is not lost -> Option A
  4. Quick Check:

    Save system = store progress [OK]
Hint: Saving means keeping progress on device storage [OK]
Common Mistakes:
  • Confusing saving with graphics or performance
  • Thinking saving connects to online servers
  • Assuming saving only affects frame rate
2. Which of the following is the correct way to write text data to a file in Unity using C#?
easy
A. File.WriteAllText(Application.persistentDataPath + "/savefile.txt", data);
B. File.ReadAllText(Application.persistentDataPath + "/savefile.txt", data);
C. File.WriteText(Application.dataPath + "/savefile.txt", data);
D. File.SaveText(Application.persistentDataPath + "/savefile.txt", data);

Solution

  1. Step 1: Identify the correct method to write text

    The method to write text to a file is File.WriteAllText.
  2. Step 2: Use the correct file path

    Application.persistentDataPath is the safe path for saving files on the device.
  3. Final Answer:

    File.WriteAllText(Application.persistentDataPath + "/savefile.txt", data); -> Option A
  4. Quick Check:

    WriteAllText + persistentDataPath = correct save [OK]
Hint: Use File.WriteAllText with persistentDataPath to save [OK]
Common Mistakes:
  • Using File.ReadAllText to write data
  • Using Application.dataPath which is not safe for saving
  • Using non-existent methods like File.SaveText
3. What will be the output of the following code snippet if the file contains '{"score": 100}'?
string path = Application.persistentDataPath + "/savefile.json";
string json = File.ReadAllText(path);
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log(data.score);
Assuming PlayerData is a class with a public int score field.
medium
A. null
B. 0
C. Error: File not found
D. 100

Solution

  1. Step 1: Read JSON string from file

    The file contains '{"score": 100}', so json will hold this string.
  2. Step 2: Deserialize JSON to PlayerData object

    JsonUtility.FromJson<PlayerData>(json) creates an object with score = 100.
  3. Step 3: Output the score field

    Debug.Log(data.score) prints 100 to the console.
  4. Final Answer:

    100 -> Option D
  5. Quick Check:

    Deserialize JSON score = 100 [OK]
Hint: JsonUtility.FromJson reads JSON into object fields [OK]
Common Mistakes:
  • Assuming score is zero if not initialized
  • Confusing ReadAllText with WriteAllText
  • Expecting null instead of a valid object
4. Identify the error in this code snippet for saving player data:
PlayerData data = new PlayerData();
data.score = 50;
string json = JsonUtility.ToJson(data);
File.WriteAllText("savefile.json", json);
medium
A. PlayerData.score must be private
B. Missing Application.persistentDataPath in file path
C. File.WriteAllText requires a byte array, not string
D. JsonUtility.ToJson cannot serialize PlayerData

Solution

  1. Step 1: Check file path usage

    The code writes to "savefile.json" without specifying a full path, which may cause saving in an unsafe or unexpected location.
  2. Step 2: Use Application.persistentDataPath for safe saving

    Unity recommends using Application.persistentDataPath + "/savefile.json" to save files safely on all platforms.
  3. Final Answer:

    Missing Application.persistentDataPath in file path -> Option B
  4. Quick Check:

    Always use persistentDataPath for file saving [OK]
Hint: Always include persistentDataPath in file paths [OK]
Common Mistakes:
  • Saving files without full path causes errors
  • Thinking JsonUtility cannot serialize simple classes
  • Confusing WriteAllText input types
5. You want to save multiple player stats (score, level, health) in a file and load them later. Which approach correctly combines JSON serialization and file saving in Unity?
hard
A. Save each stat as a separate text file using File.WriteAllText without JSON
B. Serialize stats manually to a string and save using File.ReadAllText
C. Create a PlayerStats class with fields, serialize it with JsonUtility.ToJson, then save with File.WriteAllText using Application.persistentDataPath
D. Use JsonUtility.FromJson to save data and File.WriteAllText to load data

Solution

  1. Step 1: Use a class to hold multiple stats

    A class like PlayerStats with fields score, level, health organizes data for easy serialization.
  2. Step 2: Serialize and save correctly

    JsonUtility.ToJson converts the class to JSON string; File.WriteAllText with Application.persistentDataPath saves it safely.
  3. Final Answer:

    Create a PlayerStats class with fields, serialize it with JsonUtility.ToJson, then save with File.WriteAllText using Application.persistentDataPath -> Option C
  4. Quick Check:

    Class + JsonUtility + WriteAllText + persistentDataPath = correct [OK]
Hint: Use class + JsonUtility + persistentDataPath to save/load data [OK]
Common Mistakes:
  • Saving stats separately without JSON causes complexity
  • Mixing up ReadAllText and WriteAllText roles
  • Using FromJson for saving instead of loading
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard