So I have this problem where my saved JSON file looks like this:
{
"Items": [
{ "score": { "instanceID": 24224 } },
{ "score": { "instanceID": 24224 } }
]
}
I want it to store the “score” value, which is a float. When I look to see what the value behind a “score” value, console writes “0”.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
public class InputScoreHandler : MonoBehaviour
{
[SerializeField] InputScoreEntry score;
[SerializeField] string filename;
List<InputScoreEntry> entries = new List<InputScoreEntry>();
private void Start()
{
entries = FileHandler.ReadListFromJSON<InputScoreEntry>(filename);
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Finish"))
{
entries.Add(new InputScoreEntry (score.points));
Debug.Log(score.points);
score.points = 0f;
FileHandler.SaveToJSON<InputScoreEntry>(entries, filename);
}
}
}
Here’s the InputScoreEntry code that I used in the previous script
[System.Serializable]
public class InputScoreEntry
{
public float points { get; set; }
public InputScoreEntry(float points)
{
this.points = points;
}
}
and functions from FlieHandler that I use in InputScoreHandler
public static List<T> ReadListFromJSON<T>(string filename)
{
string content = ReadFile(GetPath(filename));
if (string.IsNullOrEmpty(content) || content == "{}")
{
return new List<T>();
}
List<T> res = JsonHelper.FromJson<T>(content).ToList();
return res;
}
public static void SaveToJSON<T>(List<T> toSave, string filename)
{
Debug.Log(GetPath(filename));
string content = JsonHelper.ToJson<T>(toSave.ToArray());
WriteFile(GetPath(filename), content);
}
Also, I have the script that counts the time that the car ends the race, and there is also the value that I want to store, which is the same value I tried to save in previous scripts but in Time script it is held by float. Will this time script be a better place to save it into Json?