Storing and retrieving user data in game development is a very important aspect.
In this tutorial, we will learn in detail about how to save and load data in Unity.
There are difficult parts, but if you follow step by step, you will surely succeed, so don’t worry!
Table of Contents
- 1. The Necessity of Data Storage
- 2. How to Save Data in Unity
- 3. Saving and Loading Data with JSON
- 4. Simple Saving and Loading with PlayerPrefs
- 5. Complex Data Storage Using XML or BinaryFormatter
- 6. Practice: Implementing Data Saving and Loading
- 7. Conclusion
1. The Necessity of Data Storage
It is essential to store the player’s progress or settings while playing the game.
If data is not saved, players would have to start over every time they begin the game,
which degrades the gaming experience. For example, by saving information such as level completion, scores, and item possession,
players can maintain their progress. Here, data storage can be primarily divided into two main purposes:
- Saving the player’s game progress
- Saving game settings and options
2. How to Save Data in Unity
In Unity, data can be saved in various ways. We mainly use the following methods:
- PlayerPrefs: A way to save data with simple key-value pairs.
- JSON File: A useful method for saving structured data.
- XML File: A method for clearly defining and saving the structure of data.
- BinaryFormatter: A method to save and load objects through serialization.
3. Saving and Loading Data with JSON
JSON is a widely used format for structurally storing data. By learning how to use JSON in Unity,
you can easily save and load complex data structures. Here’s how to implement saving and loading data using JSON.
3.1 JSON Data Class
You first need to create a class that defines the data to be saved. For example, you can create a class to store player information like this:
[System.Serializable]
public class PlayerData {
public string playerName;
public int playerScore;
public float[] playerPosition;
public PlayerData(string name, int score, Vector3 position) {
playerName = name;
playerScore = score;
playerPosition = new float[] { position.x, position.y, position.z };
}
}
3.2 Saving JSON Data
You can convert the data you defined above into JSON format and save it to a file.
Here is an example of saving JSON data:
public void SaveData(PlayerData data) {
string json = JsonUtility.ToJson(data);
System.IO.File.WriteAllText(Application.persistentDataPath + "/playerdata.json", json);
}
3.3 Loading JSON Data
The method for loading the saved JSON data is as follows:
public PlayerData LoadData() {
string path = Application.persistentDataPath + "/playerdata.json";
if (System.IO.File.Exists(path)) {
string json = System.IO.File.ReadAllText(path);
return JsonUtility.FromJson<PlayerData>(json);
}
return null;
}
4. Simple Saving and Loading with PlayerPrefs
PlayerPrefs is the easiest way to save simple data.
It is primarily used for saving strings, integers, and floating-point data.
It is very straightforward to use, and you can save and load data in the following way.
4.1 Saving Data to PlayerPrefs
public void SaveScore(int score) {
PlayerPrefs.SetInt("PlayerScore", score);
PlayerPrefs.Save();
}
4.2 Loading Data from PlayerPrefs
public int LoadScore() {
return PlayerPrefs.GetInt("PlayerScore", 0); // Default value is 0
}
5. Complex Data Storage Using XML or BinaryFormatter
For complex data structures, data can be stored using XML or BinaryFormatter.
Both methods can save data in object form, with BinaryFormatter being more concise and performant, but
XML is human-readable, making it advantageous for data verification.
5.1 Saving XML Data
using System.Xml.Serialization;
public void SaveToXml(PlayerData data) {
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.xml", FileMode.Create)) {
serializer.Serialize(stream, data);
}
}
5.2 Loading XML Data
public PlayerData LoadFromXml() {
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.xml", FileMode.Open)) {
return (PlayerData)serializer.Deserialize(stream);
}
}
5.3 Saving BinaryFormatter Data
using System.Runtime.Serialization.Formatters.Binary;
public void SaveToBinary(PlayerData data) {
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.dat", FileMode.Create)) {
formatter.Serialize(stream, data);
}
}
5.4 Loading BinaryFormatter Data
public PlayerData LoadFromBinary() {
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.dat", FileMode.Open)) {
return (PlayerData)formatter.Deserialize(stream);
}
}
6. Practice: Implementing Data Saving and Loading
Let’s proceed with a simple practice based on what we have learned so far.
We will implement a feature that allows us to input the player’s name and score, save them, and later load them.
6.1 Creating the UI
Set up a UI in the Unity Editor to receive input.
Place InputField and Button, and configure it to receive player names and scores.
6.2 Writing the Script
Now, write a script to handle user input and implement the saving and loading functionality.
Test the implemented features to ensure they work correctly.
7. Conclusion
Today we learned about various methods of saving and loading data in Unity.
We learned to save simple data using PlayerPrefs, and how to handle complex data using JSON or XML.
I hope these features will be very helpful in your game development.
Always practice and find your own way to save data!
Thank you for reading! Happy gaming!