Hi I wrote a binary save system code to save game level progress,but It doesn't work.
I made a save button after finishing each level and a load button in start menu.
This is my Save System script…
using System.IO;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void SavePlayer(Player player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/Player.mre";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayer(Player player)
{
string path = Application.persistentDataPath + "/Player.mre";
if(File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.Log("Not In" + path);
return null;
}
}
and this is my save data script…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[System.Serializable]
public class PlayerData {
public int LevelNum;
public PlayerData (Player player)
{
LevelNum = SceneManager.GetActiveScene().buildIndex;
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public int LevelNum = SceneManager.GetActiveScene().buildIndex;
public void save()
{
SaveSystem.SavePlayer(this);
}
public void load()
{
PlayerData data = SaveSystem.LoadPlayer(this);
LevelNum = SceneManager.GetActiveScene().buildIndex;
}
}
and the above code is my Player Script
I put the Player script on my Canvas and save and load function for two buttons.
I want the game to get saved after each level,and when player come back it load from previous level.
Please help me…