android data doesn't save on 2nd launch

Hello, I have a basic save/load system with android. When I click on save btn or minimize my game, it’s creating/updating .dat file, when I click on load btn it’s loading data from it (I suppose). But when I launch my app second time, there’s no saving data, not even when I click on load btn.

Help me :c

using UnityEngine;
using TMPro;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

 public class Destroyer : MonoBehaviour
{
 public TextMeshProUGUI score;
 public TextMeshProUGUI debugg;
 public int i = 0;

 void Update()
 {
     score.text = "SCORE: " + i;
 }

 public void Save()
 {
     BinaryFormatter bf = new BinaryFormatter();
     FileStream file = File.Create(Application.persistentDataPath + "//score.dat");
     ScoreData data = new ScoreData();
     data.Score = i;
     debugg.text = "Debug save" + data.Score;
     bf.Serialize(file, data);
     file.Close();
 }

 public void Load()
 {
     if (File.Exists(Application.persistentDataPath + "//score.dat"))
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Open((Application.persistentDataPath + "//score.dat"), FileMode.Open);
         ScoreData data = (ScoreData)bf.Deserialize(file);
         file.Close();
         i = data.Score;
         debugg.text = "Debug load" + data.Score;
     }
 }

 public void __load() //load btn
 {
     Load();
 }
 public void __save() //save btn
 {
     Save();
 }
 void OnTriggerEnter2D(Collider2D col)
 {
     Destroy(col.gameObject);
     i++;
 }
 void OnApplicationPause()
 {
     Save();
 }
 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
 void OnBeforeSceneLoadRuntimeMethod()
 {
     Load();
 }
}

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

@dah41kj To understand the problem first you need to understand how OnApplicationPause works.

OnApplicationPause will call after awake when you first time launches your app there after every time whenever the app pauses.

First time say you have save some score 5. It will save and loads 5. But when you starts the app second time the initial value for the “i”(score) will be 0 and as I said earlier OnApplicationPause will call after awake and it save 0 (overwrite 5) and when you press load it loads 0 from the file.

Comment the code inside OnApplicationPause and test its working as your requirement.

@dah41kj you can use the below code

void OnApplicationPause(bool pauseState)
{
if(pauseState)
Save();
}

It will solve your problem :slight_smile: