I have just implemented a simple save system, but my game uses multiple scenes as levels. How do I save what scene the player is currently in as a variable so I can then load it from a different scene. Ex. Load button on main menu takes player to where they last where in a different scene.
[System.Serializable]
public class PlayerData
{
//These are the variables that need to be saved and loaded everytime
public float health;
public float[ ] position;
// This is how to locate where the variables are
//Player data
public PlayerData (PlayerController player)
{
health = player.currentHealth;
//Can not convert vector3 into binary. Break down into 3 separate floats.
position = new float[3];
position[0] = player.transform.position.x;
position[1] = player.transform.position.y;
position[2] = player.transform.position.z;
}
}
public static class SaveSystem
{
public static void SavePlayer (PlayerController player)
{
//Creates a binary file called “player” of type mog(can be any file type(mog = Method Ox Games))
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + “/player.mog”;
using (FileStream stream = new FileStream(path, FileMode.Create))
{
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data); //actually writes(streams) the (variable called “data”) to the file we created
stream.Close(); // terminates the streaming of data
}
}
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + “/player.mog”;
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(path, FileMode.Open))
{
PlayerData data = formatter.Deserialize(stream) as PlayerData; //converts binary back to original code
stream.Close();
return data;
}
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
}