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

public class SaveData : MonoBehaviour
{
    [SerializeField] private PotionData _PotionData = new PotionData();
    public void SaveIntoJson()
    {
        string potion = JsonUtility.ToJson(_PotionData);
        //System.IO.File.WriteAllText(Application.persistentDataPath + "/PotionData.json", potion);
        System.IO.File.WriteAllText(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\TombstoneSave\\PotionData.json", potion);
        Debug.Log(Application.persistentDataPath);
    }

    public void LoadJson()
    {
        //string data = System.IO.File.ReadAllText(Application.streamingAssetsPath + "/PotionData.json");
        string data = System.IO.File.ReadAllText(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\TombstoneSave\\PotionData.json");
        PotionData potionData = JsonUtility.FromJson<PotionData>(data);
        Debug.Log(potionData.potion_name);
    }
}

[System.Serializable]
public class PotionData
{
    public string potion_name;
    public int value;
    public List<Effect> effect = new List<Effect>();
}

[System.Serializable]
public class Effect
{
    public string name;
    public string desc;
}
Ask ChatGPT
Set ChatGPT API key
Find your Secret API key in your ChatGPT User settings and paste it here to connect ChatGPT with your Tutor LMS website.
Scroll to Top