SAVE & LOAD - JSON
Saving and Loading Data using JSON in Unity
On this page, we'll learn the basics of saving and loading data using JSON in Unity.
The benefit of using JSON to save game data is that the file is easy to read and modify. This is great for when you are debugging or testing your game. You can use it for a casual single-player game, but you may want to encrypt or find other solutions if you want to secure the players' data. For now, let's learn the basics.
(Not in the mood for a step-by-step guide? Here's a GitHub repository for ya!)
First, we'll go through our initialization process. Go ahead and create a class with all the data you want saved. For example:
public class PlayerData
{
public int health;
public int gold;
public Vector3 position;
}
Create a new object and add the values to your liking.
PlayerData playerData = new PlayerData();
playerData.health = 100;
playerData.gold = 5;
playerData.position = Vector3.zero;
We'll need a location for the save file to be stored. It's recommended to use Application.persistentDataPath for convenience and consistency.
string saveFilePath = Application.persistentDataPath + "/PlayerData.json";
Initialization is done! At this point our code will look like this.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class PlayerData
{
public int health;
public int gold;
public Vector3 position;
}
public class SaveLoadJSON : MonoBehaviour
{
PlayerData playerData;
string saveFilePath;
void Start()
{
playerData = new PlayerData();
playerData.health = 100;
playerData.gold = 5;
playerData.position = Vector3.zero;
saveFilePath = Application.persistentDataPath + "/PlayerData.json";
}
}
Let's move on to saving these data. There are two steps for this. First, we need to convert PlayerData to a JSON formatted string using JsonUtility.ToJson.
string savePlayerData = JsonUtility.ToJson(playerData);
Then write the JSON string to a file in the location previously set. Calling this again with the same file location and name will automatically overwrite the save file.
File.WriteAllText(saveFilePath, savePlayerData);
And saving the player data to a JSON file is done! Our save method should look like this.
public void SaveGame()
{
string savePlayerData = JsonUtility.ToJson(playerData);
File.WriteAllText(saveFilePath, savePlayerData);
}
The next step is to load data from a saved JSON file. We'll use the previously set saveFilePath for the JSON file location. First, store the content of the save file into a string.
string loadPlayerData = File.ReadAllText(saveFilePath);
Then convert this string from a JSON format back to our PlayerData format.
playerData = JsonUtility.FromJson<PlayerData>(loadPlayerData);
That's it for loading! Here are a couple of useful things to manage your saving/loading systems. First is checking if a saved file exists. This will return a bool value.
File.Exists(saveFilePath)
Then if you'd like to delete a save file, use this next line.
File.Delete(saveFilePath)
So, loading and deleting JSON files will look like this.
public void LoadGame()
{
if (File.Exists(saveFilePath))
{
string loadPlayerData = File.ReadAllText(saveFilePath);
playerData = JsonUtility.FromJson<PlayerData>(loadPlayerData);
}
}
public void DeleteSaveFile()
{
if (File.Exists(saveFilePath))
{
File.Delete(saveFilePath);
}
}
After combining everything we learned, our final saving and loading script will look like this. I added some inputs and debugging tools so you can jump straight in and test it out in Unity! You'll be able to see the JSON file at the save file location and open it to read the data.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class PlayerData
{
public int health;
public int gold;
public Vector3 position;
}
public class SaveLoadJSON : MonoBehaviour
{
PlayerData playerData;
string saveFilePath;
void Start()
{
playerData = new PlayerData();
playerData.health = 100;
playerData.gold = 5;
playerData.position = Vector3.zero;
saveFilePath = Application.persistentDataPath + "/PlayerData.json";
}
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
SaveGame();
if (Input.GetKeyDown(KeyCode.L))
LoadGame();
if (Input.GetKeyDown(KeyCode.D))
DeleteSaveFile();
}
public void SaveGame()
{
string savePlayerData = JsonUtility.ToJson(playerData);
File.WriteAllText(saveFilePath, savePlayerData);
Debug.Log("Save file created at: " + saveFilePath);
}
public void LoadGame()
{
if (File.Exists(saveFilePath))
{
string loadPlayerData = File.ReadAllText(saveFilePath);
playerData = JsonUtility.FromJson<PlayerData>(loadPlayerData);
Debug.Log("Load game complete! \nPlayer health: " + playerData.health + ", Player gold: " + playerData.gold + ", Player Position: (x = " + playerData.position.x + ", y = " + playerData.position.y + ", z = " + playerData.position.z + ")");
}
else
Debug.Log("There is no save files to load!");
}
public void DeleteSaveFile()
{
if (File.Exists(saveFilePath))
{
File.Delete(saveFilePath);
Debug.Log("Save file deleted!");
}
else
Debug.Log("There is nothing to delete!");
}
}
Aaaand that's it! Now that you have the basics of saving and loading to a JSON file, you can build up by adding features like save slots, autosave, and more! Check out this GitHub repository to see the example we created for this topic. Feel free to download the script and test it out yourself. Have fun!
Level up your game development by finding more stuff to learn in our growing list of pixel-sized tutorials.