Save and load JSON in Unity

Jak zapisać dane do formatu (pliku) JSON i jak wczytać dane z JSON do Unity?

W przykładzie pokazane jest jak zapisać plik w bezpiecznej ścieżce (persistentDataPath) lub na pulpicie

[System.Serializable]
public class SavePoints
{
    public int points;
}
using UnityEngine;

public class SaveLoad : MonoBehaviour
{
    string path;
    SavePoints savePoints = new SavePoints();

    private void Awake()
    {
        //path = $"{Application.persistentDataPath}/saveload.json";
        path = $"{System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop)}\\saveload.json";
    }


    public void Save(int i)
    {
        savePoints.points = i;
        string s = JsonUtility.ToJson(savePoints);
        System.IO.File.WriteAllText(path, s);
    }

    public SavePoints Load()
    {
        if(System.IO.File.Exists(path))
        {
            string loadedJson = System.IO.File.ReadAllText(path);
            SavePoints loadedSave = JsonUtility.FromJson<SavePoints>(loadedJson);
            Debug.Log(loadedSave.points);
            return loadedSave;
        }
        else
        {
            savePoints.points = 0;
            return savePoints;
        }
    }
}

using TMPro;
using UnityEngine;

public class PlayerPi : MonoBehaviour
{
    [SerializeField] TMP_Text txt;
    [SerializeField] SaveLoad saveLoad;

    int points = 0;

    private void Start()
    {
        points = saveLoad.Load().points;
        DisplayPoints();
    }
    void Update()
    {
        if (Input.GetButtonDown("Fire3")) AddPoint();
    }

    void AddPoint()
    {
        points++;
        DisplayPoints();
        saveLoad.Save(points);
    }

    void DisplayPoints()
    {
        txt.text = points.ToString();
    }
}
Scroll to Top