- Home /
Problem with my binary files
Hi, i'm saving data in binary files, is my first time doing this, and i have a problem, when i compile the game, in my computer save and load data correctly, but in other compuers not work. I don't know whats happen, someone can help me?, thanks so much.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class SaveData
{
public bool[] isActive;
public int[] highScores;
public int[] stars;
}
public class GameData : MonoBehaviour
{
public static GameData gameData;
public SaveData saveData;
// Start is called before the first frame update
void Awake()
{
if (gameData == null)
{
DontDestroyOnLoad(this.gameObject);
gameData = this;
}
else
{
Destroy(this.gameObject);
}
Load();
}
void Start()
{
}
public void Save()
{
//Create a binary formatter which can binary files
BinaryFormatter formatter = new BinaryFormatter();
//Create a route from the program to the file
FileStream file = File.Open(Application.persistentDataPath + "/GameData.dat", FileMode.Create);
//Create a copy of my save data
SaveData data = new SaveData();
data = saveData;
//Actually save the data in the file
formatter.Serialize(file, data);
//close the data stream
file.Close();
Debug.Log("Saved Data");
}
public void Load()
{
//Check if the save gmae file exists
if (File.Exists(Application.persistentDataPath + "/GameData.dat"))
{
//Create a Binary Formatter
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/GameData.dat", FileMode.Open);
saveData = formatter.Deserialize(file) as SaveData;
file.Close();
Debug.Log("Loaded Data");
}
}
void OnApplicationQuit()
{
Save();
}
void OnDisable()
{
Save();
}
}
On what systems/versions are you running your application ? Do you have error logs when trying to load a file from a different computer ?
In window 10, they are two similar pc and, no, i don't have nothing error logs. In my computer work fine, but in the my friend computer and in my laptop not work.
At least, do you see the Loaded Data
debug message when trying to load the file?
Answer by Bunny83 · Sep 29, 2019 at 10:32 PM
That's why you should never mess with any kind of path strings manually by concatenating string fragments. You should always use System.IO.Path.Combine(). It should work properly on on all systems (linux, mac, android == forward slash, windows == backslash). It also should deal with potential leading or trailing slashes automatically.
So in your case:
string fileName = System.IO.Path.Combine(Application.persistentDataPath, "GameData.dat");