Hello folks!
Sorry for not posting anything over the last few weeks — I was away for Diwali holidays and caught up with some other work. But I’m back now!
In my last blog post, we talked about PlayerPrefs, which was the first entry in my “Different Ways of Storing Game Data” series. Today, we’ll look at another way to store data in Unity — using JSON and XML files.
What is JSON?
For those who don’t know, JSON stands for JavaScript Object Notation. It’s a lightweight text format that’s easy for both humans and machines to read and write. Because of its simplicity, JSON has become the standard for transferring and storing data across different systems.
JSON is language-independent, meaning you can use it with almost any programming language once you understand its structure. It stores data as key-value pairs, separated by commas. JSON supports numbers, booleans, strings, arrays, objects, and null values.
Here’s a simple example of JSON:
{
"firstName": "John",
"lastName": "Doe",
"isEmployed": true,
"skills": ["JavaScript", "Python", "SQL"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
(I’ll leave some useful links at the end where you can learn more about JSON and XML.)
What is XML?
XML stands for Extensible Markup Language. It’s similar to HTML in structure but unlike HTML, XML is extensible — meaning you can define your own custom tags to describe the data.
XML doesn’t “do” anything by itself; it’s just a structured way of storing and describing information using tags. It’s also widely used for data storage and transfer, though it’s typically more verbose than JSON.
Here’s an example of what XML looks like:
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J. K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
How to Use JSON in Unity
Using JSON in Unity is straightforward.
To store data in JSON format, you first need to convert your data into a JSON string using JsonUtility.ToJson().
To read or parse that data, you can use JsonUtility.FromJson() to convert it back into your desired C# type (either a built-in type or a custom class).
JSON files are typically stored in Application.persistentDataPath, so they persist between sessions. You can also create subfolders inside that path to organize your saves.
Here’s the structure of what it might look like in code:
using UnityEngine;
using System.IO;
[System.Serializable]
public class PlayerData
{
public int level;
public int coins;
public string playerName;
}
public class JsonSaveSystem : MonoBehaviour
{
private string savePath;
private void Awake()
{
savePath = Path.Combine(Application.persistentDataPath, "playerSave.json");
}
public void SaveGame()
{
PlayerData data = new PlayerData()
{
level = 5,
coins = 200,
playerName = "Rahul"
};
string json = JsonUtility.ToJson(data, true);
File.WriteAllText(savePath, json);
Debug.Log("Game saved to: " + savePath);
}
public void LoadGame()
{
if (File.Exists(savePath))
{
string json = File.ReadAllText(savePath);
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log($"Loaded: Level {data.level}, Coins {data.coins}, Name {data.playerName}");
}
else
{
Debug.LogWarning("No save file found!");
}
}
}
💡Note: Unity’s built-in JsonUtility is fast but limited. It doesn’t handle nested lists or dictionaries well.
For more advanced cases, you can use the Newtonsoft JSON package (Json.NET), which supports more complex data structures.
How to Use XML in Unity
To work with XML in Unity, you’ll use the XmlSerializer class.
- Create an
XmlSerializerinstance for your data type. - Create a
FileStreamto write your data to disk. - Use the
Serialize()method to write your object as XML to the file. - To read data, do the same but call
Deserialize()instead.
Just like JSON, XML files are stored inside Application.persistentDataPath so your data remains saved between sessions.
Here’s a simple structure for XML in code:
using UnityEngine;
using System.IO;
using System.Xml.Serialization;
[System.Serializable]
public class PlayerDataXML
{
public int level;
public int coins;
public string playerName;
}
public class XmlSaveSystem : MonoBehaviour
{
private string savePath;
private void Awake()
{
savePath = Path.Combine(Application.persistentDataPath, "playerSave.xml");
}
public void SaveGame()
{
PlayerDataXML data = new PlayerDataXML()
{
level = 5,
coins = 200,
playerName = "Rahul"
};
XmlSerializer serializer = new XmlSerializer(typeof(PlayerDataXML));
using (FileStream stream = new FileStream(savePath, FileMode.Create))
{
serializer.Serialize(stream, data);
}
Debug.Log("Game saved (XML) to: " + savePath);
}
public void LoadGame()
{
if (File.Exists(savePath))
{
XmlSerializer serializer = new XmlSerializer(typeof(PlayerDataXML));
using (FileStream stream = new FileStream(savePath, FileMode.Open))
{
PlayerDataXML data = (PlayerDataXML)serializer.Deserialize(stream);
Debug.Log($"Loaded (XML): Level {data.level}, Coins {data.coins}, Name {data.playerName}");
}
}
else
{
Debug.LogWarning("No XML save file found!");
}
}
}
⚠️ Note: XML is great for readability and structured data but is generally heavier and slower compared to JSON.
Use it when you specifically need hierarchical tagging or compatibility with systems that expect XML.
Key Takeaway
JSON and XML are both excellent choices for saving structured data in Unity.
- Use JSON when you want lightweight, human-readable data with quick serialization and deserialization.
- Use XMLwhen your data needs a more descriptive structure or you’re working with systems that rely on XML.
Both methods are great for saving player progress, inventory data, or custom level information — especially when you want control over your save files.
Top comments (0)