Question by
IlisanVlad · Sep 25, 2018 at 05:03 PM ·
androiderrorunity 2dplayerprefssave
Android Game Save and Load doesn't work
I tried a few different codes but none of them work on my android device...I retrieve the data with this command " GameManager.Instance.gemsToSave"
The code:
public static GameManager Instance { get; private set; }
public float highscoreToSave;
public int coinsToSave;
public int gemsToSave;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else if(Instance != this)
{
Destroy(gameObject);
}
}
private void OnEnable()
{
Load();
}
private void OnDisable()
{
Save();
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData();
data.highScore = highscoreToSave;
data.coins = coinsToSave;
data.gems = gemsToSave;
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
highscoreToSave = data.highScore;
coinsToSave = data.coins;
gemsToSave = data.gems;
}
}
}
[Serializable] class PlayerData { public float highScore; public int coins; public int gems;
}
Thanks!
Comment
Your answer
Follow this Question
Related Questions
ArgumentException: Requested value 'X86' was not found. Unity 2019.4.1f1 0 Answers
Apk on android does not start. Reason: Animator | Не запускается Apk на андройд. Причина: Animator 0 Answers
esfesfesff 1 Answer
PlayerPrefs works fine in Unity Editor but not on Android 0 Answers
Are playerprefs a safe way of saving data or not?? 2 Answers