Unity Save/Load JSON File Tutorial in 10 Minutes

How to load and save to json file

using System.Collections.Generic;

public class GameData
{
    public int numberOfChip;
    public int numberOfPoints;
    public List<int> listOfCoordinatesToPlacedTheChip;
    public int initialPointsOfChips;
    public int winningPointsOfChips;
    public int numberOfConnects;
    public List<int> listOfConnectsBetweenCouplePoints;
}
using System.IO;
using UnityEngine;

public class DataManager : MonoBehaviour
{
    private GameData data;
    private string file = "player.txt";

    public GameData Data => data;

    public void Load()
    {
        data = new GameData();
        string json = ReadFromFIle(file);
        JsonUtility.FromJsonOverwrite(json, data);
    }

    public void Save()
    {
        string json = JsonUtility.ToJson(data);
        WriteToFile(file, json);
    }

    private void WriteToFile(string fileName, string json)
    {
        string path = GetFilePath(fileName);
        FileStream fileStream = new FileStream(path, FileMode.Create);

        using (StreamWriter writer = new StreamWriter(fileStream))
        {
            writer.Write(json);
        }
    }

    private string ReadFromFIle(string fileName)
    {
        string path = GetFilePath(fileName);
        if (File.Exists(path))
        {
            using (StreamReader reader = new StreamReader(path))
            {
                string json = reader.ReadToEnd();
                return json;
            }
        }
        else
        {
            Debug.LogWarning("File not found");
        }

        return "Success";
    }

    private string GetFilePath(string fileName)
    {
        return Application.persistentDataPath + "/" + fileName;
    }

    private void OnApplicationPause(bool pause)
    {
        if (pause) Save();
    }
}
using UnityEngine;
using UnityEngine.UI;

public class UI: MonoBehaviour
{
    private DataManager gameData;
    public InputField playerName;
    public Text coins;
    
    // Start is called before the first frame update
    void Start()
    {
        gameData = new DataManager();
        gameData.Load();
        coins.text = gameData.Data.numberOfChip.ToString();
    }

    public void ClickCoin()
    {
        //in video add coins is not save.use for this operation action
        coins.text = gameData.Data.numberOfChip.ToString();
    }

    public void ChangeName(string text)
    {
        //in video add coins is not save.use for this operation action
    }

    public void ClickSAve()
    {
        gameData.Save();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *