- Home /
Cannot load a saved game
Hello,
I tried to save a game, next close the game, and then load the game. But although I saved it, when I press the LOAD button in during gameplay, it would not load anything, not even load the saved position. Here is the save/load code that I wrote so far.
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveManager
{
public static string directory = "SaveData";
public static string fileName = "player.game";
public static void SaveGame(Player player)
{
if (!(DirectoryExists()))
{
Directory.CreateDirectory(Application.persistentDataPath + "/" + directory);
}
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(GetFullPath());
Save sav = new Save(player);
bf.Serialize(file, sav);
Debug.Log("Your game has been saved.");
file.Close();
}
public static Save LoadGame()
{
if (SaveExists())
{
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(GetFullPath(), FileMode.Open);
Save sav = (Save)bf.Deserialize(file);
Debug.Log("Your game has been loaded.");
file.Close();
return sav;
}
catch (SerializationException)
{
Debug.LogError("Failed to save file");
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static bool DirectoryExists()
{
return Directory.Exists(Application.persistentDataPath + "/" + directory);
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + directory + "/" + fileName;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Save
{
public int score;
public int lives;
public int health;
public float[] position;
public Save(Player player)
{
score = player.score;
lives = player.lives;
health = player.health;
position = new float[2];
position[0] = player.transform.position.x;
position[1] = player.transform.position.y;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public int score;
public int lives;
public int health;
public void Save()
{
SaveManager.SaveGame(this);
}
public void Load()
{
Save sav = SaveManager.LoadGame();
score = sav.score;
lives = sav.lives;
health = sav.health;
Vector2 position;
position.x = sav.position[0];
position.y = sav.position[1];
transform.position = position;
}
}
Can anyone help? Any assistance would be appreciated.
Sincerely, burchland2
Answer by Bunny83 · Sep 09, 2021 at 04:26 PM
Well, saving and loading / restoring all this information involves many tiny things and a lot things in between could fail. So what have you already done to debug your issue? First of all, do you get any errors or warnings? Have you tried adding more Debug.Log statements across your code? Also try logging the position that is loaded to see if it gets back as you had expected. Finally Your issue could be some sort of race condition. Maybe your loading happens before some other script overwrites your changes? We don't know when or where your Save and Load methods get called. That's something you have to check yourself, we can not do that for you, we don't have your project ^^.
I just like to add that I saw a lot of similar code by other peoples. I guess this is based on some tutorial. That said, first and foremost, the BinaryFormatter should not be used anymore for anything because it's a security risk. Since most get that "security risk" wrong, let me be more clear. This is not about people cheating or altering values in your save. This is about actual security because manipulated save files could cause arbitary code execution of malicious code. So by using the BinaryFormatter you put your user at that risk. Here's the security guide by Microsoft itself. Also, most choose the BinaryFormatter because they think it makes their saved data more secure (in terms of cheating) which is not really the case anyways.
Another critique point about this concept is where the data is handled. The Save constructor takes a player reference and populates itself with the information from the player. However at deserialization the task of reversing the data is carried out by the player class. This is generally a bad design. The serialization and deserialization should be in the same class and the corresponding save and load functions should be "opposites" from each other. In this case the Save function takes a Player instance, the Load function should as well and the deserialization should be handled inside the SaveManager or the Save class.
Your answer
![](https://koobas.hobune.stream/wayback/20220613042819im_/https://answers.unity.com/themes/thub/images/avi.jpg)