Hi, I have a project originally using binary formatter to save data and decided to switch to Json, but have been struggling to get it to work ever since. I use a code to set my serializable health to my player’s current health every time it takes damage or gains hp but If I try to load, the health just starts at 0.
Edit:Sorry for the messy looking code again, can someone tell me how to post scripts, can’t find the guideline that is suppose to show me and am getting frustrated with the automated correction.
Here are the scripts I used for saving my player’s health:
{
public static string directory = "/SaveData/";
public static string fileName = "MyData.txt";
public static void Save(Maxplayerhealth.SaveHealth health)
{
string dir = Application.persistentDataPath + directory;
if (Directory.Exists(dir))
Directory.CreateDirectory(dir);
string json = JsonUtility.ToJson(health);
File.WriteAllText(dir + fileName, json);
}
public static Maxplayerhealth.SaveHealth Load()
{
string fullPath = Application.persistentDataPath + directory + fileName;
Maxplayerhealth.SaveHealth health = new Maxplayerhealth.SaveHealth();
if(File.Exists(fullPath))
{
string json = File.ReadAllText(fullPath);
health = JsonUtility.FromJson<Maxplayerhealth.SaveHealth>(json);
}
else
{
Debug.Log("Save file does not exist");
}
return health;
}
}
public SaveHealth saveH;
public static int maxhealth;
{
public int playerHealth = 100;
public static bool intitle;
void Start()
{
Debug.Log(saveH.savehealth);
maxhealth = playerHealth;
if (intitle)
{
StartCoroutine(sethealth());
}
healthBar.SetMaxHealth(maxhealth);
}
[System.Serializable] public class SaveHealth
{
public int savehealth;
public int savecurrency;
}
IEnumerator sethealth()
{
yield return new WaitForSeconds(.1f);
maxhealth = saveH.savehealth;
healthBar.SetMaxHealth(maxhealth);
healthBar.SetHealth(playerHealth);
}
private void Update
{
if (healthcollected == true)
{
maxhealth += 10;
upgradedHealth += 10;
playerHealth = maxhealth;
healthBar.SetMaxHealth(maxhealth);
healthcollected = false;
saveH.savehealth = playerHealth;
Debug.Log(saveH.savehealth + " saveHP");
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(“Enemy”) || collision.gameObject.CompareTag(“Spike”) && canbedamage == true)
{
Physics2D.IgnoreLayerCollision(7, 9, true);
Physics2D.IgnoreLayerCollision(7, 14, true);
canbedamage = false;
StartCoroutine(Invulnerable());
playerHealth -= damage;
saveH.savehealth = playerHealth;
healthBar.SetHealth(playerHealth);
Damageanimate();
}
}
if (Input.GetKeyDown(KeyCode.W))
{
StartCoroutine(SavePlayer());
}
if (intitle == true)
{
intitle = false;
LoadPlayer();
}
IEnumerator SavePlayer()
{
yield return new WaitForSeconds(3.5f);
Debug.Log("SaveThis");
JsonSaveManager.Save(health);
}
public void LoadPlayer()
{
health = JsonSaveManager.Load();
}