In this lesson, you will learn how to leverage Unity’s JsonUtility to transform complex C# data structures into human-readable JSON strings for efficient save-game persistence.
The Power of Native Serialization
While formats like Binary or XML have their place, JsonUtility is a high-performance, built-in tool optimized for Unity’s specific architecture. It provides a lightweight way to bridge the gap between your in-game runtime objects and a persistent text file on disk. Because JSON is text-based, it is invaluable for debugging player save files or tweaking configuration data without needing a custom binary editor.
Implementing the Serialization Flow
To serialize an object, the class must be marked with the [System.Serializable] attribute. JsonUtility will then scan the class fields and convert them into a JSON-formatted string.
Consider a simple PlayerData class:
[System.Serializable]
public class PlayerData {
public string playerName;
public int level;
public float[] position;
}
// Serialization process
PlayerData data = new PlayerData { playerName = "Hero", level = 10, position = new float[] { 0, 1, 0 } };
string jsonString = JsonUtility.ToJson(data, true); // 'true' enables pretty-printing
System.IO.File.WriteAllText(Application.persistentDataPath + "/save.json", jsonString);
Constraints and Considerations
It is critical to remember that JsonUtility is designed for speed and simplicity. It does not support complex polymorphic types, dictionary types, or circular references out of the box. If your game architecture relies heavily on deep inheritance hierarchies or nested dictionaries, you would typically need to flatten your data structure into simple arrays or lists before passing it to JsonUtility. By keeping your "Save Objects" as simple Data Transfer Objects (DTOs), you ensure the serialization process remains performant and avoids unnecessary garbage collection spikes—a recurring theme in our performance-focused phase.
When loading, you simply reverse the process using JsonUtility.FromJson<PlayerData>(jsonString), which reconstructs your C# object directly from the disk file.
Key Takeaway: Use JsonUtility to maintain high-performance, human-readable data persistence by keeping your serializable classes structured as simple, non-circular data containers.