i followed the data persistence tutorial on unity and created a save and load function for my game. However for some strange reason whenever i call these functions, it saves the script but only till the application is closed. when the game is opened after being saved, and after trying to reload the file on start up, it doesn’t reload it like it should, it acts as though it didn’t retrieve the file at all. what could be wrong?
persistence data code
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class Persistent : MonoBehaviour
{
public static Persistent persistent;
public int[] HighScores;
public int SquishCoins;
public int Volume;
public int Score;
public bool isSwipe;
public bool isSound;
// Use this for initialization
void Start()
{
if (persistent == null)
{
DontDestroyOnLoad(gameObject);
persistent = this;
}
else if (persistent != this)
{
Destroy(gameObject);
}
}
// Update is called once per frame
void Update()
{
Score = ScoreTime.score.Score;
}
public void Savethis()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "Playerdata");
Playerspecs data1 = new Playerspecs();
data1.HighScores = persistent.HighScores;
data1.isSound = persistent.isSound;
data1.isSwipe = persistent.isSwipe;
data1.SquishCoins = persistent.SquishCoins;
data1.Volume = persistent.Volume;
data1.Score = persistent.Score;
data1.Score = persistent.Score;
bf.Serialize(file, data1);
file.Close();
}
public void Loadthis()
{
if (File.Exists(Application.persistentDataPath + "Playerdata"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "Playerdata", FileMode.Open);
Playerspecs data1 = (Playerspecs)bf.Deserialize(file);
file.Close();
persistent.HighScores = data1.HighScores;
persistent.isSwipe = data1.isSwipe;
persistent.isSound = data1.isSound;
persistent.Volume = data1.Volume;
persistent.SquishCoins = data1.SquishCoins;
}
}
}
[Serializable]
class Playerspecs
{
public int[] HighScores;
public int SquishCoins;
public int Score;
public int Volume;
public bool isSwipe;
public bool isSound;
}
code accessing persistence data code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class script : MonoBehaviour {
Persistent persistent;
public void MainMenuLoad()
{
SceneManager.LoadScene("MainMenu", LoadSceneMode.Single);
}
public void Save()
{
Persistent.persistent.Savethis();
}
public void Load()
{
Persistent.persistent.Loadthis();
}
// Use this for initialization
void Start () {
Load();
}
// Update is called once per frame
void Update () {
}
}