- Home /
Saving JSON didnt work
Im trying to create save and load script, the loading is working, but the saving is not working. I dont know what is wrong with my script, can someone help me?
using UnityEngine;
using System.IO;
[System.Serializable]
public class PlayerData
{
public int skor = score.skorupdate;
}
public class SaveSystem : MonoBehaviour
{
[SerializeField] private PlayerData data = new PlayerData();
public void SavePlayer()
{
string json = JsonUtility.ToJson(data);
File.WriteAllText(Application.persistentDataPath + "/save.json", json);
Debug.Log("Saved!");
}
public void LoadPlayer()
{
if (File.Exists(Application.persistentDataPath + "/save.json"))
{
string json = File.ReadAllText(Application.persistentDataPath + "/save.json");
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
score.skorupdate = data.skor;
Debug.Log("Loaded!");
}
else
{
Debug.Log("File Not Found In" + Application.persistentDataPath + "/save.json");
}
}
}
We need to know where you keep the score variable. Try debugging it by doing
Debug.Log("Saved! skor " + data.skor);
Found it, here. I dont know why its always on 0
{"skor":0}
Answer by rh_galaxy · Oct 26, 2021 at 06:46 AM
It is 0 because score.skorupdate is 0 at start where you create data, you don't update it when you do the save. We need code for the score variable, but you can try this:
//[SerializeField] private PlayerData data = new PlayerData(); //remove this line
public void SavePlayer()
{
PlayerData data = new PlayerData(); //and put it here
string json = JsonUtility.ToJson(data);
File.WriteAllText(Application.persistentDataPath + "/save.json", json);
Debug.Log("Saved! skor " + data.skor);
}
Thanks, It's worked. I hope you have a good day
Your answer
Follow this Question
Related Questions
Checkpoint autosave Method? 0 Answers
Can gameobject be exported as unity3d form? 0 Answers
Save and Load System of multiple objects in scene? 2 Answers
SerializationException: Type UnityEngine.Vector3 is not marked as Serializable. 1 Answer
Saving Melee Combat Template Pack (MY LAST PROBLEM) 1 Answer