How can I get the script to load what has been saved?
Hi I'm having trouble making my script save and load the game progress, like saving every time the player passes the level and when he's in mine he uses the load game function. What is solving this problem is that I put the save function in the "D" which is the character's movement key, but I'm not able to make the script load what was saved, I've tried several things but it's not working right.
Note: My game is 2D
This is the script that saves the game
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine.UI;
public class SalvarDados : MonoBehaviour { public Checkpoint checkpoint; public Vector3 temp; public Button Fire1;
// Start is called before the first frame update
void Start()
{
temp = transform.position;
}
// Update is called once per frame
void Update()
{ //
if (Input.GetKeyDown(KeyCode.D))
{
print ("salvo" + Application.persistentDataPath);
Salvar();
}
// Fire1 faz parte da configuração da unity, é o padrão
if (Input.GetButton ("Fire1"))
{
LoadPos();
}
}
void Salvar()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(Application.persistentDataPath + "/posData.data");
SaveClass s = new SaveClass();
s.posx = transform.position.x;
bf.Serialize(fs, s);
fs.Close();
}
void LoadPos()
{
if (File.Exists(Application.persistentDataPath + "/posData.data"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Open(Application.persistentDataPath + "/posData.data", FileMode.Open);
SaveClass s = (SaveClass)bf.Deserialize(fs);
fs.Close();
temp.x = s.posx;
transform.position = temp;
}
}
} [Serializable] class SaveClass { public float posx; }
And this is the one on the menu that makes the game start and quit, but I can't make the game continue loading what was saved
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System.IO; using UnityEngine.UI; using System;
public class Menu : MonoBehaviour { public Button Fire1;
public void Iniciar()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
void LoadPos()
{
//tá salvando, só não tá restornando pelo botao de continuar
if (File.Exists(Application.persistentDataPath + "/posData.data"))
{
// olhar na video aula a condição do if pq a vc configuro o botao dentro da unity
Fire1.interactable = true;
}
}
public void Sair()
{
Application.Quit();
}
void verificarSalvarJogo()
{
}
}