Save from file and Load to file through BinaryWriter and BinaryReader

Hello,

This time, I want to save the exact position of the player GameObject within the exact scene to a file, and then load it from a file. Here is what I have so far:

SaveManager.cs:

public class SaveManager : MonoBehaviour
{
    public static string fileName;
    public static string saveDirectory;

    public PlayerController ball;

    public float x;

    public float y;

    void Start()
    {
        ball = FindObjectOfType<PlayerController>();
        x = ball.myBod.position.x;
        y = ball.myBod.position.y;
    }

    public void Save()
    {
        saveDirectory = Application.persistentDataPath + "/saveFile.txt";
        using (BinaryWriter writer = new BinaryWriter(File.Open(saveDirectory, FileMode.Create)))
        {
            writer.Write(HealthManager.playerHealth);
            writer.Write(LivesSystem.lives);
            writer.Write(ScoreSystem.score);
            writer.Write(x);
            writer.Write(y);
        };
    }

    public void Load()
    {
        saveDirectory = Application.persistentDataPath + "/saveFile.txt";
        if (File.Exists(saveDirectory))
        {
            using (BinaryReader reader = new BinaryReader(File.Open(saveDirectory, FileMode.Open)))
            {
                HealthManager.playerHealth = reader.ReadInt32();
                LivesSystem.lives = reader.ReadInt32();
                ScoreSystem.score = reader.ReadInt32();

                x = reader.ReadSingle();
                y = reader.ReadSingle();
            }
        }
    }
}

GameManager.cs:

public class GameManager : MonoBehaviour
{
    public PauseScreen ps;
    public SaveManager sm;

    void Start()
    {
        ps = FindObjectOfType<PauseScreen>();
        sm = FindObjectOfType<SaveManager>();
    }


    public void Load()
    {
        sm.Load();
        ps.Resume();
    }

    public void Save()
    {
        sm.Save();
    }
}

Can someone please help with this? Any would be appreciated.

Sincerely,
burchland2

You have tried different approaches now and not got it to work, and binary writer and reader is not any safer when it comes to cheating, and is unreadable in debugging. I always use to have my files in plain text, that way you can verify both the writer (either done in a text editor or from your game) and the reader (parsing of the text)… You can do it as a .json file if you want to be more main stream, but I use my own format.

Example for a level

*MAPTYPE MISSION
*MAPSIZE  48 60
*MAPFILE  mission12.txt
*TILESET  ts_frost.tga
*MAXPLAYERS 1
*PLAYERSTARTPOS   212   872
*GRAVITY 0.1 70.0 //default if not set
...

And when parsing I do this:

bool LoadPass1()
{
    szFileText = System.Text.Encoding.UTF8.GetString(File.ReadAllBytes(Application.persistentDataPath + "/" + i_szFilename));
    szLines = szFileText.Split((char)10);

    //to parse 0.00 as float on any system
    CultureInfo ci = new CultureInfo("en-US");
    bool bFinished = true;

    while (iLineIndex < szLines.Length - 1)
    {
        iLineIndex++;
        char[] szSeparator = { (char)32 };
        string[] szTokens = szLines[iLineIndex].Trim('\r', '

').Split(szSeparator, StringSplitOptions.RemoveEmptyEntries);
if (szTokens.Length == 0) continue;
if (szTokens[0].Length == 0) continue;
if (!szTokens[0].StartsWith(“*”)) continue;

        bFinished = false;
        if (szTokens[0].CompareTo("*MAPTYPE") == 0)
        {
            //...
        }
        else if (szTokens[0].CompareTo("*GRAVITY") == 0)
        {
            //update how to read floats with ci
            vGravity.x = float.Parse(szTokens[1], ci.NumberFormat);
            vGravity.y = -float.Parse(szTokens[2], ci.NumberFormat);
        }
        //continue with other text commands
        //...

May not be what you want to hear, but really saving and loading files is not a problem, It should work on your approach as well, but it doesn’t so…


Update: If you use floating points it’s no good storing them as binary, especially if you share your files among different systems.