Hello,
I have a problem. I created two buttons, one to save and the other to load. Although I can save a state of my game, I somehow can’t load it. The code is below.
Sincerely,
burchland2
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class SaveSystem : MonoBehaviour
{
public Vector2 savedLocation;
int lives;
int score;
public PauseScreen ps;
void Start()
{
ps = FindObjectOfType<PauseScreen>();
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/player.dat");
PlayerInfo data = new PlayerInfo();
data.lives = lives;
data.score = score;
data.xPos = this.gameObject.transform.position.x;
data.yPos = this.gameObject.transform.position.y;
savedLocation = this.gameObject.transform.position;
bf.Serialize(file, data);
file.Close();
Debug.Log("Your game has been saved.");
}
public void Load()
{
ps.Resume();
if(File.Exists(Application.persistentDataPath + "/player.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/player.dat", FileMode.Open);
PlayerInfo data = (PlayerInfo)bf.Deserialize(file);
file.Close();
lives = data.lives;
score = data.score;
this.gameObject.transform.position = new Vector2(data.xPos, data.yPos);
Debug.Log("Your game has been loaded.");
}
else
{
Debug.Log("Your game can't be found.");
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Checkpoint"))
{
Save();
Debug.Log("Saved from Checkpoint");
}
}
}
[System.Serializable]
public class PlayerInfo
{
public float xPos;
public float yPos;
public int lives;
public int score;
}