Unity Save System problem

Started by
3 comments, last by kelly74 4 years, 4 months ago

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…

Advertisement

Do you expect

PlayerData data = SaveSystem.LoadPlayer(this);

to load the scene for you?

If so, this won't work! Scenes have to be loaded calling Unity's SceneManager.Load functions and they can't be serialized as you are just saving the scene nothing else

@Shaarigan Thanks for your reply ,but please give me a solution.

which part of code should I change?

You are storing and restoring the level ID in build order. Use the Unity Engine Manual to find out how to convince SceneManager to load a scene by ID

This topic is closed to new replies.

Advertisement