Trying to get score data to save into a json file from score script

I am trying to get my score in my score script to constantly update into a json file so that I can move onto trying to get it appropriated for a high score system and am just starting small before I move on. However, so far what I have tried just generates a json file with nothing in it. Any tips would be greatly appreciated. You will see that I put in the code that should save the data in the json file in the update part of the script.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Klaviactor.ScoreBoards;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
using Unity.VisualScripting;



public class Test : MonoBehaviour
{
    public TMP_Text Score;
    public int scoreAmount = 0;
    
   


  
    // Start is called before the first frame update
    void Start()
   
   
    {
       
        scoreAmount = 0;
        Score = GetComponent<TMP_Text>();
        scoreAmount = PlayerPrefs.GetInt("scoreKey");
       
       






    }




    void Update()

    {
        string json = JsonUtility.ToJson(Score);
        Debug.Log(json);

        using (StreamWriter writer = new StreamWriter(Application.dataPath + Path.AltDirectorySeparatorChar + "ScoreData.json"))
        {
            writer.Write(json);
        }

        {
            Score.text = scoreAmount.ToString();
            PlayerPrefs.SetInt("scoreKey", scoreAmount);
        }
    }
       
   
   
  

    public void AddScore()
    {
        scoreAmount += 1;
        Score.text = "" + scoreAmount;
       

    }

   public void SubtractScore()
    {
        scoreAmount -= 1;
    }

    public void DeleteScoreKey()

    {
       
    }

    public void ReturnToMenu()

    {
        SceneManager.LoadScene(1);
        PlayerPrefs.DeleteKey("scoreKey");
    }

    private void OnApplicationQuit()
    {
        PlayerPrefs.DeleteKey("scoreKey");
    }
}

I would NOT constantly write to disk. Terrible idea.

Also you are trying to write a Unity component to disk. Do not do that too as it generally does not work. Use a plain C# object instead.

StreamWriter stuff is unnecessary in basic situations as well.

For example:

[System.Serializable]
public class GameState
{
    public int Score = 0;
}

// example code only
GameState state = new GameState()
{
    Score = 100
};

string json = JsonUtility.ToJson(state);
path = Application.persistantDataPath + "/Score.txt";
File.WriteAllText(path, json);

Reading is just File.ReadAllText + Json.FromJson.

You should only write to disk when you would lose the data, and read it when you need to restore it. For example a singleton game object could read this when it creates itself, an write the value to disk when the application closes. Doesn’t need to be any more complicated than that.

Do you realize that Update is called 60 times a second?

I kind of see what you are saying and tried implementing that into my own theory into a better light, but it did not work, maybe you could have a look at what I tried from what you showed and see if you notice anything specific. If it saved a score file I could not find it anywhere. I have to update the save pretty much ever click if possible so that when the timer runs out and the script is no longer active I can call on the saved file for high score dictation. I also tried “/Score.json” as well and that did not work either.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Klaviactor.ScoreBoards;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
using Unity.VisualScripting;



public class Test : MonoBehaviour
{
    public TMP_Text Score;
    public int scoreAmount = 0;
   
    public void SaveToJson()
   
   
    {
        if (Input.GetMouseButtonDown(0)) ;
        {
            SaveToJson();
        }
    }


    private void Awake()
    {
        Test scoreData = new Test();
        string json = JsonUtility.ToJson(scoreData);
        string path = Application.persistentDataPath + "/Score.txt";
        File.WriteAllText(path, json);
        Debug.Log(path);
    }

You realise nothing is going to call SaveToJson?

That whole method makes absolutely no sense.

Also you should not new() a monobehaviour. Didn’t I just tell you not to serialize Unity objects?

I’m starting to think the OP is just a troll.

So I figured it out and it was simple, so I had to just use the method as seen below which I added to my Subtract Score and Add Score public void where I created a class that it called on from a string that was designated as System.Serializable and similar to the methods that were similar as suggested by Spiney.

Here is the code from my score script that is all in the only affected areas.

public void AddScore()
    {
        scoreAmount += 1;
        Score.text = "" + scoreAmount;

        ScoreJSON ScoreNumber = new ScoreJSON();
        ScoreNumber.Amount = Score.text;

        string json = JsonUtility.ToJson(ScoreNumber, true);
        File.WriteAllText(Application.dataPath + "/ScoreNumber.json", json);
       




    }

   public void SubtractScore()
    {
       
        ScoreJSON ScoreNumber = new ScoreJSON();
        ScoreNumber.Amount = Score.text;

        string json = JsonUtility.ToJson(ScoreNumber, true);
        File.WriteAllText(Application.dataPath + "/ScoreNumber.json", json);
        scoreAmount -= 1;
    }

then the separate class file that I had to have in order for it to work.

[System.Serializable]

public class ScoreJSON

{
    public string Amount;
}

You now just have two methods now that do pretty much the same thing. Like I said before you should only read/write to disk when completely necessary. Otherwise during gameplay you can just operate entirely on a score value in memory.

Could look like this:

public sealed class ScoreSystem : Monobehaviour
{
    private static ScoreSystem _instance;
   
    private static readonly string _scoreDataPath = $"{Application.persistantDataPath}/Score.txt";
   
    private ScoreData _scoreData;
   
    private void Awake()
    {
        bool exists = File.Exists(_scoreDataPath);
        if (exists == true)
        {
            string json = File.ReadAllText(_scoreDataPath);
            _scoreData = JsonUtility.FromJson(json);
        }
        else
        {
            _scoreData = new ScoreData();
        }
    }
   
    private void OnDestroy()
    {
        string json = JsonUtility.ToJson(_scoreData);
        File.WriteAllText(_scoreDataPath, json);
    }
   
    private static void EnsureSingleton()
    {
        if (_instance == null)
        {
            return;
        }
       
        var gameObject = new GameObject("ScoreSystem");
        _instance = gameObject.AddComponent<ScoreSystem>();
        Object.DontDestroyOnLoad(_instance.gameObject);
    }
   
    public static void ModifyScore(int value)
    {
        EnsureSingleton();
       
        var score = _instance._scoreData;
        score.Score += value;
    }
}

[System.Serializable]
public class ScoreData
{
    public int Score;
}
1 Like