- Home /
Problem is not reproducible or outdated
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
Answer by rh_galaxy · Sep 22, 2021 at 08:11 PM
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', '\n').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.
Thank you very much for your feedback, rh_galaxy. Your reply doesn't sound harsh or unreasonable at all. It's just the answer I required. After all, I forgot to say that I need a safe and secure procedure anyway. So although I could possibly sound like a noob about this, how do I go about saving and loading a game in JSON format in a safe, secure, and "unhackable" manner? (I already know that unhackable isn't a real term.)
Sincerely, burchland2
When you give the program to someone on the internet there is no security any more. If your program is not well spread you get away with it, but if it's popular someone will/can hack it if they want to.
What's the implication if someone does?
My approach are to record a replay of the game inputs, that can be seen by other players and it is very hard to fake a replay so it doesn't look fake, and thus can be detected, but very hard to prevent sending in the fake replay.
A json file is just plain text so no better for cheating purposes. There are inbuilt json -libraries to use I think.
Any progress?
Sorry, I solved the problem on my own. Thanks for all of your feedback, guys.