Skip to content

Instantly share code, notes, and snippets.

@ElonGame
Forked from MarcelvanDuijnDev/SaveLoad_JSON.cs
Created January 5, 2025 04:52
Show Gist options
  • Save ElonGame/64998fda8ab0061976b4c9042621ee44 to your computer and use it in GitHub Desktop.
Save ElonGame/64998fda8ab0061976b4c9042621ee44 to your computer and use it in GitHub Desktop.

Revisions

  1. @MarcelvanDuijnDev MarcelvanDuijnDev revised this gist Jan 8, 2022. No changes.
  2. @MarcelvanDuijnDev MarcelvanDuijnDev created this gist Jan 8, 2022.
    52 changes: 52 additions & 0 deletions SaveLoad_JSON.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    using System.Collections.Generic;
    using System.IO;
    using UnityEngine;

    public class SaveLoad_JSON : MonoBehaviour
    {
    private Json_SaveData _SaveData = new Json_SaveData();

    void Start()
    {
    LoadData();
    }

    public void SaveData()
    {
    string jsonData = JsonUtility.ToJson(_SaveData, true);
    File.WriteAllText(Application.persistentDataPath + "/SaveData.json", jsonData);
    }
    public void LoadData()
    {
    try
    {
    string dataAsJson = File.ReadAllText(Application.persistentDataPath + "/SaveData.json");
    _SaveData = JsonUtility.FromJson<Json_SaveData>(dataAsJson);
    }
    catch
    {
    SaveData();
    }
    }
    public Json_SaveData GetSaveData()
    {
    return _SaveData;
    }
    public void CreateNewSave()
    {
    Json_ExampleData newsave = new Json_ExampleData();
    newsave.exampleValue = 10;
    _SaveData.saveData.Add(newsave);
    }
    }

    [System.Serializable]
    public class Json_SaveData
    {
    public List <Json_ExampleData> saveData = new List<Json_ExampleData>();
    }
    [System.Serializable]
    public class Json_ExampleData
    {
    public float exampleValue = 0;
    }