- Home /
Can save the game, but cannot load it back
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;
}
Answer by burchland2 · Apr 18, 2021 at 04:13 PM
@HellsHand None. That's the problem. I couldn't load the values from where I previously saved the game.
So what your saying is that there is absolutely nothing in the console when you try to load the data?
Yes, except for the debug log line, but that's it. Maybe I should rearrange what I am re-instantiating, such as (in this case, score, lives, and position) above the File.Close(); line.
Edit: Strike that. I tried rearranging the lines. No success. Can anyone be of additional assistance?
Sorry, guys.
I solved this problem a long time ago. I should have updated this post.
Your answer
