Question by
zachmallet · Oct 21, 2016 at 04:20 AM ·
scenescene-loadingloadingscene-switchingscene change
Save and load scene from file
Hello I am encountering some trouble. I want player to be able to save there scene and load it from the main menu then they press "Load Last Save". Here is my Save Code
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData();
data.health = Player.myPlayer.currentPlayerHealth;
data.soulCount = Player.myPlayer.SoulAmount;
data.posx = Player.myPlayer.transform.position.x;
data.posy = Player.myPlayer.transform.position.y;
data.posz = Player.myPlayer.transform.position.z;
data.scene = SceneManager.GetActiveScene();
data.sceneName = SceneManager.GetActiveScene().name;
bf.Serialize(file, data);
file.Close();
Debug.Log("Saving Game.");
}
Here is my load code:
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
SceneManager.LoadScene(data.sceneName, LoadSceneMode.Single);
Vector3 PlayerPos = new Vector3(data.posx,data.posy,data.posz);
Player.myPlayer.currentPlayerHealth = data.health;
Player.myPlayer.SoulAmount = data.soulCount;
Player.myPlayer.transform.position = PlayerPos;
Debug.Log("Loading Game.");
}
}
Here is the function that is being called from the main menu on click:
public void load()
{
GameControl.control.Load();
}
What I currently have is not working, and I though that would be the correct soultion. Thanks for any help!
Comment
Answer by Skizmo · Oct 21, 2016 at 03:59 PM
What is not working ? Is the file saved correctly ? Is the file loaded but processed incorreclty ?
Answer by wmeadows · Oct 21, 2016 at 04:09 PM
I used that same tutorial. Make sure that you have actually instantiated your instance of global control.
Yeah I have a game control game object in the start menu and and the level.