Save and Load using JSON file in Unity - c#

Save and Load using JSON  file in Unity -  c#

Save and Load using JSON  file in Unity -  c#


To save and load data using JSON files in Unity, you can use the JsonUtility class, which is part of the UnityEngine namespace. This class provides methods for serializing objects to and from JSON format.

Example 1:

Here is an example of how you can use JsonUtility to save and load data in Unity:

using UnityEngine;

public class SaveLoadExample : MonoBehaviour
{
    public int score;
    public string playerName;

    private void Start()
    {
        // Load the data from a JSON file
        string jsonData = File.ReadAllText("save.json");
        SaveData data = JsonUtility.FromJson<SaveData>(jsonData);
        score = data.score;
        playerName = data.playerName;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            // Save the data to a JSON file
            SaveData data = new SaveData();
            data.score = score;
            data.playerName = playerName;
            string jsonData = JsonUtility.ToJson(data);
            File.WriteAllText("save.json", jsonData);
        }
    }
}

[System.Serializable]
public class SaveData
{
    public int score;
    public string playerName;
}

In this example, we have a SaveData class that contains the data we want to save (the player's score and name). When the player presses the "S" key, we create an instance of SaveData and populate it with the current values of score and playerName. We then use the JsonUtility.ToJson method to convert the SaveData object to a JSON string, which we write to a file called "save.json" using the File.WriteAllText method.

When the game starts, we use the File.ReadAllText method to read the contents of the "save.json" file into a string, and then use the JsonUtility.FromJson method to convert the JSON string back into a SaveData object. We can then assign the values from the SaveData object to the score and playerName variables.

Note that the SaveData class must have the System.Serializable attribute in order for it to be serialized by JsonUtility.


Example 2:

In Unity, you can use the JsonUtility class to serialize and deserialize objects to and from JSON strings. Here's an example of how you can use it to save and load a simple object to and from a JSON file:

using UnityEngine;
using System.Collections;

public class SaveLoadExample : MonoBehaviour
{
    public class Data
    {
        public int score;
        public string name;
    }

    void Start()
    {
        // Save the object to a JSON file
        Data data = new Data();
        data.score = 100;
        data.name = "Player";
        string json = JsonUtility.ToJson(data);
        System.IO.File.WriteAllText("save.json", json);

        // Load the object from a JSON file
        string jsonFromFile = System.IO.File.ReadAllText("save.json");
        Data dataFromJson = JsonUtility.FromJson<Data>(jsonFromFile);
        Debug.Log(dataFromJson.name + " has a score of " + dataFromJson.score);
    }
}

This example demonstrates how to save and load a Data object, which has two fields: score and name. The JsonUtility.ToJson method is used to convert the object to a JSON string, which is then saved to a file using the System.IO.File.WriteAllText method. To load the object from the JSON file, the System.IO.File.ReadAllText method is used to read the contents of the file into a string, and then the JsonUtility.FromJson method is used to deserialize the string into a Data object.

Keep in mind that this is just a simple example, and you may need to handle more complex cases (such as handling errors or missing fields) in your actual implementation.

Example 3:

To save data to a JSON file in Unity, you can use the JsonUtility class which is part of Unity's UnityEngine.JsonUtility namespace. Here's an example of how you can use JsonUtility to save a simple data object to a JSON file:

using UnityEngine;
using System.IO;

public class SaveLoadExample : MonoBehaviour
{
    // The data object we want to save
    public class PlayerData
    {
        public string name;
        public int score;
    }

    // The path to the save file
    private string saveFilePath = "Assets/save.json";

    public void Save()
    {
        // Create a new PlayerData object and populate it with some data
        PlayerData data = new PlayerData
        {
            name = "Player1",
            score = 100
        };

        // Convert the data object to a JSON string
        string json = JsonUtility.ToJson(data);

        // Write the JSON string to the save file
        File.WriteAllText(saveFilePath, json);
    }
}

To load data from a JSON file in Unity, you can use the JsonUtility.FromJson method which deserializes a JSON string and returns an object of the specified type. Here's an example of how you can use JsonUtility.FromJson to load a PlayerData object from a JSON file:

using UnityEngine;
using System.IO;

public class SaveLoadExample : MonoBehaviour
{
    // The data object we want to save
    public class PlayerData
    {
        public string name;
        public int score;
    }

    // The path to the save file
    private string saveFilePath = "Assets/save.json";

    public void Load()
    {
        // Read the JSON string from the save file
        string json = File.ReadAllText(saveFilePath);

        // Deserialize the JSON string and create a new PlayerData object
        PlayerData data = JsonUtility.FromJson<PlayerData>(json);

        // Use the data from the PlayerData object
        Debug.Log("Name: " + data.name + ", Score: " + data.score);
    }
}

Keep in mind that the data object you want to save or load with JsonUtility must have the [System.Serializable] attribute in order for it to be serialized or deserialized.

I hope this helps! Let me know if you have any questions.