Writing to a file
- Game Development course
- Advanced
- Lesson 21/71
- 4 min
Learn to write to a file with Application.persistentDataPath.
Safe File Path: persistentDataPath
Across platforms like desktop, iOS, and Android, write permissions do not exist in the installation folder. Unity resolves this by providing Application.persistentDataPath, a dedicated safe write directory for every OS.
using System.IO;
// Cross-platform safe path construction
string path = Path.Combine(Application.persistentDataPath, "save.json");The Path.Combine method automatically selects the appropriate path separator slash for the target operating system.
Writing to Disk with File.WriteAllText
The most convenient way to write a serialized JSON string to disk is via System.IO.File.WriteAllText. This method creates the file if missing, or overwrites it if it already exists.
using System.IO;
string json = "{\"health\": 100}";
File.WriteAllText(path, json);Wrapping file writing operations inside try-catch blocks is recommended to catch permission or storage issues.
Practice Creating save file path
Define a Start method. Inside, declare string dosyaAdi = "save.json"; and print "Kayit dosyasi: " + dosyaAdi to the console.
Starter code
using UnityEngine;
public class SaveWriter : MonoBehaviour
{
// Start icinde dosyaAdi tanimla ve yazdir
}Sample solution
using UnityEngine;
public class SaveWriter : MonoBehaviour
{
void Start()
{
string dosyaAdi = "save.json";
Debug.Log("Kayit dosyasi: " + dosyaAdi);
}
}Expected output
Kayit dosyasi: save.json
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which Unity path should be used to reliably write game save files across various operating systems?
- Application.temporaryCachePath
- Application.persistentDataPath Correct answer
- Application.dataPath
- Application.streamingAssetsPath
Explanation: Application.persistentDataPath is the dedicated path across all platforms reserved for persisting user data safely.
2 Write text to file
File.____(filePath, jsonContent);
File.WriteAllText(filePath, jsonContent);
Explanation: The 'File.WriteAllText' method is used to write text content directly into a file.
3 File writing terms
| Term | Meaning |
|---|---|
persistentDataPath |
Platform-specific safe save directory |
Path.Combine |
Safely joins directory and file name |
File.WriteAllText |
Writes text to a file in one operation |
StreamWriter |
Stream-based file writing class |