problem with loading data with serialization in the right time
Hello all,
I made a save system and it works fine but the problem is first health and other data loading then scene is loading so in the new scene my character can`t get the right data. I want to know should I make it work? here is the codes, a collider trigger active the saveData() then it interact with gameManager to save and then a button can load later.
public class saveLoadData : MonoBehaviour {
gameManager theGM;
// Use this for initialization
void Awake () {
theGM = gameManager.instance;
}
// Update is called once per frame
void Update () {
}
public void saveData()
{
if (!Directory.Exists(Application.dataPath + "SavedGames"))
Directory.CreateDirectory(Application.dataPath + "/SavedGames");
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(Application.dataPath + "/SavedGames/save.db");
saveManager saveManager = new saveManager();
saveManager.currentLevel = theGM.getCurrentLevel();
saveManager.currentHealth = theGM.getCurrentHealth();
saveManager.currentRounds = theGM.getCurrentRounds();
bf.Serialize(fs, saveManager);
Debug.Log("Game Saved!");
fs.Close();
}
public void loadData()
{
if(File.Exists(Application.dataPath + "/SavedGames/save.db"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Open(Application.dataPath + "/SavedGames/save.db", FileMode.Open);
saveManager saveManager = (saveManager)bf.Deserialize(fs);
fs.Close();
theGM.loadLastLevel(saveManager.currentLevel);
theGM.loadLastHealth(saveManager.currentHealth);
theGM.loadLastRounds(saveManager.currentRounds);
}
if(!File.Exists(Application.dataPath + "/SavedGames/save.db"))
{
Debug.Log("No saved file present!");
}
}
}
[System.Serializable]
class saveManager
{
public int currentLevel;
public float currentHealth;
public int currentRounds;
}
and here is gameManager:
public class gameManager : MonoBehaviour {
public static gameManager instance;
playerController myPC;
playerHealth myPH;
// Use this for initialization
void Awake () {
if(instance == null)
{
instance = this;
}
else if(instance != this)
{
Destroy(gameObject);
}
}
void Start()
{
myPC = GameObject.FindGameObjectWithTag("Player").GetComponent<playerController>();
myPH = GameObject.FindGameObjectWithTag("Player").GetComponent<playerHealth>();
}
// Update is called once per frame
void Update () {
}
//loading data
public void loadLastLevel(int x)
{
SceneManager.LoadScene(x);
}
public void loadLastHealth(float h)
{
myPH.currentHealth = h;
myPH.healthSlider.value = h;
}
public void loadLastRounds(int r)
{
myPC.remainingRounds = r;
}
//getting data
public int getCurrentLevel()
{
return SceneManager.GetActiveScene().buildIndex;
}
public float getCurrentHealth()
{
return myPH.currentHealth;
}
public int getCurrentRounds()
{
return myPC.remainingRounds;
}
}
I am really appreciate for any help
Comment