- Home /
Question by
burchland2 · Sep 11, 2021 at 05:57 PM ·
saveload
SaveManager not working
Hi,
I have a problem with loading a saved file. Saving the file is absolutely no problem. Only loading it. Here is the code. Any assistance will be appreciated.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class SaveManager : MonoBehaviour
{
public int score = 0;
public int lives = 9;
public int health = 3;
public static string directory = "SaveLoad";
public static string fileName = "saveFile.sav";
public float[] position = new float[2];
public Player player;
public PlayerData data;
public void Start()
{
data = new PlayerData(player);
score = data.Score;
lives = data.Lives;
health = data.Health;
}
public void Save()
{
if (!DirectoryExists())
{
Directory.CreateDirectory(Application.persistentDataPath + "/" + directory);
}
string savePath = Application.persistentDataPath + "/" + directory + "/" + fileName;
using (var w = new BinaryWriter(File.OpenWrite(savePath)))
{
w.Write(System.Convert.ToInt32(score));
w.Write(System.Convert.ToInt32(lives));
w.Write(System.Convert.ToInt32(health));
w.Write(System.Convert.ToSingle(position[0]));
w.Write(System.Convert.ToSingle(position[1]));
}
Debug.Log("Your game has been saved.");
}
public void Load()
{
string loadPath = Application.persistentDataPath + "/" + directory + "/" + fileName;
using (var r = new BinaryReader(File.OpenRead(loadPath)))
{
score = r.ReadInt32();
lives = r.ReadInt32();
health = r.ReadInt32();
position[0] = r.ReadSingle();
position[1] = r.ReadSingle();
}
Debug.Log("Your game has been loaded.");
}
private static bool DirectoryExists()
{
return Directory.Exists(Application.persistentDataPath + "/" + directory);
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + directory + "/" + fileName;
}
}
Comment
Your answer