In this lesson, you will learn how to design hierarchical data models that allow you to organize massive amounts of game progress into clean, manageable JSON structures for reliable local storage.
Moving Beyond Flat Data
As your game grows, saving a single "Level" integer or "Score" float is no longer enough. You need to capture inventory states, quest progress, and world transformations. The secret to complex serialization is nested composition. Instead of creating one giant SaveData class with hundreds of variables, you should break your game logic into smaller, dedicated classes that mirror your actual game architecture.
Designing the Hierarchy
To keep your JSON organized, define discrete serializable classes for different domains of your game. For instance, define a PlayerStats object, an InventoryItem list, and a WorldState object. By nesting these inside a master SaveGame container, you ensure that your JSON file remains readable and debuggable, which is critical when tracking down save-corruption issues.
[System.Serializable]
public class SaveData {
public PlayerStats player;
public List<InventoryItem> inventory;
public WorldState world;
}
[System.Serializable]
public class PlayerStats {
public int level;
public float health;
}
Why Structure Matters
When you structure your data this way, you gain two massive advantages:
- Maintainability: You can modify the
InventoryItemstructure without touching yourPlayerStatslogic. - Performance: By using discrete classes, you can implement partial saving or loading. If only the player’s position has changed, you don't necessarily have to re-serialize the entire static world data if you've designed your save system to handle subsets of your
SaveDataobject.
Always ensure every class is marked with [System.Serializable] and that your variables are public or decorated with [SerializeField]. This allows Unity’s JsonUtility to traverse the object graph effectively. If your hierarchy becomes too deep, consider how these objects reference each other; stick to unique identifiers (like GUID strings) rather than object references, as JSON does not support circular references natively.
Key Takeaway: Design your data models as hierarchical, decoupled classes to ensure your JSON files remain organized, scalable, and easy to maintain as your game complexity increases.