A Beginner’s Guide to Storing and Retrieving Data in Unity

santosh parihar
6 min readNov 6, 2023

--

Unity, allows you to create fantastic games. But to make your game truly interactive and dynamic, you need to know how to store and retrieve data at runtime. In this beginner-friendly guide, we’ll explore the various methods for managing data in Unity, using easy-to-understand examples.

Why Store Data in Unity?

Storing data in your Unity game is essential for various reasons. It allows you to:

  • Save and load player progress.
  • Store high scores and statistics.
  • Manage game settings and configurations.
  • Keep track of in-game items, such as player inventory.
  • Create dynamic and data-driven game behavior.

Now, let’s dive into some simple ways to achieve these goals.

1. PlayerPrefs :

  • PlayerPrefs is the easiest way to store and retrieve simple data.
    PlayerPrefs stores data in key-value pairs, where the keys are strings and the values can only be strings, floats, or integers.
  • This data is saved on the player’s device, making it suitable for storing small amounts of information that need to persist between game sessions.
  • PlayerPrefs is cross-platform, meaning it works on multiple platforms supported by Unity, such as Windows, macOS, Android, iOS, and more.
    It’s important to note that PlayerPrefs is not suitable for storing sensitive or critical data, as the stored data can be accessed and modified by users with some technical knowledge.

Here’s how you can use it:

// Storing Data:

// Save a high score
int highScore = 1000;
PlayerPrefs.SetInt("HighScore", highScore);
PlayerPrefs.Save();
Retrieving Data:

// Load the high score
int loadedHighScore = PlayerPrefs.GetInt("HighScore", 0); // 0 is the default value

2. JSON :

  • In Unity, JSON (JavaScript Object Notation) is commonly used for data serialization and deserialization.
  • JSON is a lightweight data interchange format that is easy for humans to read and write.
  • Unity provides built-in support for working with JSON data, making it convenient for tasks like saving and loading game data, configuration files, and communication with web services. Here’s an overview of using JSON in Unity:

Serialization and Deserialization:

Unity allows you to easily convert C# objects to JSON format (serialization) and vice versa (deserialization). You can use the JsonUtility class for this purpose. Here’s a basic example:

  • Use JsonUtility.ToJson() to serialize objects into JSON strings.
  • To deserialize JSON data into C# objects, you can use JsonUtility.FromJson().

Example :
Let’s use an example of storing player score, name, trophy count, and win status using JSON in Unity. First, you’ll need to create a C# class to represent the player data:

public class Example : MonoBehaviour {


void Start()
{

SaveData();
LoadData();
}

[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerScore;
public int trophyCount;
public bool hasWon;
}


//Now, let's see how to use JSON to save and load this player data:

//Saving Player Data (Serialization)

//To save the player's data to a JSON file, you can create an instance of the PlayerData class, set its values, and then serialize it to a JSON string:

PlayerData player = new PlayerData
{
playerName = "John",
playerScore = 1000,
trophyCount = 5,
hasWon = true
};



public void SaveData()
{
string json = JsonUtility.ToJson(player);
// Save the JSON data to a file (you can replace "playerData.json" with your desired file path)
System.IO.File.WriteAllText("playerData.json", json);
}

//Loading Player Data (Deserialization)

// To load the player data from the JSON file and use it in your game, you can read the JSON data from the file, then deserialize it back into a PlayerData object:


public void LoadData()
{
string json = System.IO.File.ReadAllText("playerData.json");

PlayerData loadedPlayer = JsonUtility.FromJson<PlayerData>(json);

// Now you can access the loaded player data
string playerName = loadedPlayer.playerName;
int playerScore = loadedPlayer.playerScore;
int trophyCount = loadedPlayer.trophyCount;
bool hasWon = loadedPlayer.hasWon;

// Use the loaded data in your game
Debug.Log($"JSON Player Name: {playerName} , Score {playerScore} ,Trophy Count : {trophyCount} , Has Won : {hasWon} ");


}
}

The “playerData.json” will look like this :

{“playerName”:”John”,”playerScore”:1000,”trophyCount”:5,”hasWon”:true}

  • In this example, we created a PlayerData class to represent the player’s information and used JsonUtility to serialize and deserialize this data to and from a JSON format. You can adapt this code to save and load player data in your Unity game.

NOTE :

  • JSON, being a text-based format, can be more expensive for machines to parse, slower to read, and can use more memory compared to binary formats. So, if you have lots of data, you may want to consider options that aren’t text-based.

3. Scriptable Objects — Flexible Data Containers :

  • A ScriptableObject in Unity is a powerful asset type that allows you to create and manage custom data objects. Here’s a more detailed explanation of ScriptableObjects:
  • https://medium.com/p/dc0699c55b21

4. XML (Extensible Markup Language):

  • It is a text-based markup language designed for storing and exchanging structured data. It uses a human-readable and self-descriptive format, making it easy for both humans and machines to understand. XML data is organized using tags and attributes, which define the structure of the data.
  • In Unity, you can use XML to store and exchange structured data such as game configurations, level data, and other settings. To work with XML in Unity, you can use the System.Xml namespace, which provides classes for reading and writing XML data.

Here’s how you can use XML to store and retrieve player data in Unity:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[Serializable]
public class PlayerData
{
public string playerName;
public int playerScore;
public int trophyCount;
public bool hasWon;
}

public class XmlSerializationExample : MonoBehaviour
{
void Start()
{
// Create a new PlayerData instance
PlayerData player = new PlayerData
{
playerName = "John",
playerScore = 1000,
trophyCount = 5,
hasWon = true
};

// Serialize the PlayerData instance to an XML file
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
using (FileStream stream = new FileStream("playerData.xml", FileMode.Create))
{
serializer.Serialize(stream, player);
}

// Deserialize the XML data back into a PlayerData object
using (FileStream stream = new FileStream("playerData.xml", FileMode.Open))
{
PlayerData loadedPlayer = (PlayerData)serializer.Deserialize(stream);

// Now you can access the loaded player data
string playerName = loadedPlayer.playerName;
int playerScore = loadedPlayer.playerScore;
int trophyCount = loadedPlayer.trophyCount;
bool hasWon = loadedPlayer.hasWon;

// Use the loaded data in your game
Debug.Log($"XML Player Name: {playerName} , Score {playerScore} ,Trophy Count : {trophyCount} , Has Won : {hasWon} ");
}
}
}
  • In this example, we use the XmlSerializer class to serialize the PlayerData object to an XML file and then deserialize it back into a PlayerData object. The System.Xml namespace is used to work with XML data in C#.

5. Binary formats:

  • are data representations that use a binary encoding scheme, where data is stored in a form that is not human-readable.
  • These formats are designed for efficiency, compactness, and speed when it comes to data storage and transmission.
  • Unlike text-based formats such as JSON, where data is represented as human-readable characters, binary formats use numerical values and predefined structures to encode data.

Here are a few common binary formats:

1. Protobuf:

  • Protocol Buffers (protobuf) is a binary serialization format developed by Google. It’s designed to be more efficient in terms of speed, size, and processing overhead compared to text-based formats like JSON. Here’s how protobuf compares to JSON:
  • Protobuf is generally faster to parse than JSON. This is because Protobuf is a binary format, and parsing binary data is typically faster and more efficient than parsing text data.
  • JSON is human-readable, making it easy to inspect and edit, even without specific tooling. Protobuf, being a binary format, is not human-readable without decoding tools.

2. MessagePack:

  • MessagePack is another binary serialization format that is known for its simplicity and efficiency. It’s designed for space and speed.

example :

 [MessagePackObject]
public class MyClass
{
// Key attributes take a serialization index (or string name)
// The values must be unique and versioning has to be considered as well.

[Key(0)]
public int trophyCount { get; set; }

[Key(1)]
public string playerName { get; set; }

[Key(2)]
public int playerScore { get; set; }

// All fields or properties that should not be serialized must be annotated with [IgnoreMember].
[IgnoreMember]
public string address { get; set ; }
}

void ParseData()
{

var mc = new MyClass
{
trophyCount = 10,
playerName = "santy",
playerScore = 100,
};

// Call Serialize/Deserialize, that's all.
byte[] bytes = MessagePackSerializer.Serialize(mc);
MyClass mc2 = MessagePackSerializer.Deserialize<MyClass>(bytes);

// You can dump MessagePack binary blobs to human readable json.
// Using indexed keys (as opposed to string keys) will serialize to MessagePack arrays,
// hence property names are not available.
// [10,"santy",100]

var json = MessagePackSerializer.ConvertToJson(bytes);
Console.WriteLine(json);

}

for more information please visit :
https://github.com/MessagePack-CSharp/MessagePack-CSharp

3. BinaryFormatter:

  • The BinaryFormatter is a class in the .NET Framework that is used for serializing and deserializing objects in a binary format.
    BinaryFormatter is insecure and can’t be made secure according to Microsoft. So never use it.

Hope you liked it.

Support My Work ☕️

If you’ve found value in this article and would like to support my writing efforts, consider buying me a coffee. Your contribution helps me continue creating content like this.

Buy me a Coffee

Thank you for your support!

--

--