Can’t read json file for unity deserializing

I am trying to use json serialization to save data for my unity game. I have a game object with some bool variables and want to save it. I start serializing the object and it works, i have the json file with all the things inside, but when i use the read all method in the file i cant read anything. Thi is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using System.Linq;
using System.IO;

[System.Serializable]
public class LevelState : MonoBehaviour
{
    public static LevelState Instance;
    public bool boss1 = false;
    public bool gate1 = false;
    public bool Lvl2 = false;
    public bool Lvl3 = false;
    public bool boss2 = false;
    public bool gate2 = false;
    public bool end = false;
    public int difficolta;

    private string json;
    private string dataDirPath = "";
    private string dataFileName = "";
    private List<LevelState> datas;
    public void DifficultyChange(int diff)
    {
        difficolta = diff;
    }
    public void NewGame()
    {
        Instance = this;
    }
    public void Save()
    {
        string fullPath = Path.Combine(dataDirPath, dataFileName);
        json = JsonUtility.ToJson(Instance, true);
        Debug.Log(json);
        FileStream stream = new FileStream(fullPath, FileMode.Create);
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(json);
    }
    public void Load()
    {
        string fullPath = Path.Combine(dataDirPath, dataFileName);
        LevelState loaded = null;
        if(File.Exists(fullPath))
        {
            Debug.Log(fullPath);
            FileStream stream = new FileStream(fullPath, FileMode.Open);
            StreamReader reader = new StreamReader(stream);
            string dataToload = reader.ReadToEnd();
            Instance = JsonUtility.FromJson<LevelState>(dataToload);
            Debug.Log(dataToload);
            Debug.Log("loaded");
        }


        if (Instance == null)
        {
            NewGame();
        }
    }

    private void OnApplicationQuit()
    {
        Save();
    }

    private void Awake()
    {
        dataFileName = "data.json";
        dataDirPath = Application.persistentDataPath;
        Debug.Log(Application.persistentDataPath);
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
        DontDestroyOnLoad(gameObject);

    }
}
Can’t read json file for unity deserializing

4 thoughts on “Can’t read json file for unity deserializing

Leave a Reply