using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveLoadSystem
{
// Define a path to save the game data file
private static string savePath = Application.persistentDataPath + "/gameData.dat";
// Save the game data to file
public static void SaveGame(GameData data)
{
// Create a binary formatter to serialize the game data
BinaryFormatter formatter = new BinaryFormatter();
// Create a file stream to write the game data to file
FileStream fileStream = new FileStream(savePath, FileMode.Create);
// Serialize the game data and write it to the file stream
formatter.Serialize(fileStream, data);
// Close the file stream
fileStream.Close();
}
// Load the game data from file
public static GameData LoadGame()
{
// Check if the game data file exists
if (File.Exists(savePath))
{
// Create a binary formatter to deserialize the game data
BinaryFormatter formatter = new BinaryFormatter();
// Create a file stream to read the game data from file
FileStream fileStream = new FileStream(savePath, FileMode.Open);
// Deserialize the game data from the file stream
GameData data = formatter.Deserialize(fileStream) as GameData;
// Close the file stream
fileStream.Close();
// Return the loaded game data
return data;
}
else
{
// If the game data file does not exist, return null
Debug.LogError("Game data file not found.");
return null;
}
}
}
[System.Serializable]
public class GameData
{
public int score;
public bool isGameOver;
// Add any other game data variables here
}
In this script, we first define a savePath
variable to store the path where we want to save the game data file.
The SaveGame()
function takes in a GameData
object as input and serializes it using a BinaryFormatter
, which allows us to convert the data to binary format for storage. We then create a FileStream
to write the binary data to file, and close the file stream once we’re done.
The LoadGame()
function checks if the game data file exists at the savePath
location. If it does, we create a BinaryFormatter
to deserialize the data from the file stream and return it as a GameData
object. If the file does not exist, we return null.
Finally, we define a GameData
class to store any game data variables we want to save and load.
You can use this script in your game by calling SaveLoadSystem.SaveGame(data)
to save your game data and SaveLoadSystem.LoadGame()
to load it. Make sure to fill in the GameData
object with any relevant game data before saving, and update your game based on the loaded data after loading.