How do you save, write, and load from a file?
I just need to know how to create a file, write variables into the file, and then load them out of the file and save into variables in the script. In c#
Answer by KoenigX3 · Jan 16, 2017 at 11:01 PM
There are a lot of tutorials about this on the internet. I will show you how to create a custom variable holder class and serialize / deserialize it.
First, you need to create a custom class and create variables in it, which you want to store.
[System.Serializable]
public class GameData
{
public int score;
public string name;
public float timePlayed;
public GameData(int scoreInt, string nameStr, float timePlayedF)
{
score = scoreInt;
name = nameStr;
timePlayed = timePlayedF;
}
}
This is a basic GameData class which can hold a score integer, a name string, and the playtime in float. The constructor method below can be used to create an instance of this class and serialize it in a file - we will use that later.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class save : MonoBehaviour {
int currentScore = 0;
string currentName = "Asd";
float currentTimePlayed = 5.0f;
void Start()
{
SaveFile();
LoadFile();
}
public void SaveFile()
{
string destination = Application.persistentDataPath + "/save.dat";
FileStream file;
if(File.Exists(destination)) file = File.OpenWrite(destination);
else file = File.Create(destination);
GameData data = new GameData(currentScore, currentName, currentTimePlayed);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, data);
file.Close();
}
public void LoadFile()
{
string destination = Application.persistentDataPath + "/save.dat";
FileStream file;
if(File.Exists(destination)) file = File.OpenRead(destination);
else
{
Debug.LogError("File not found");
return;
}
BinaryFormatter bf = new BinaryFormatter();
GameData data = (GameData) bf.Deserialize(file);
file.Close();
currentScore = data.score;
currentName = data.name;
currentTimePlayed = data.timePlayed;
Debug.Log(data.name);
Debug.Log(data.score);
Debug.Log(data.timePlayed);
}
}
In this script, we are using other namespaces as well. There are 3 variables in the game - we will save them into a file, and then read them. The Debug.Log() function will return the data which was read from the file.
The destination will use the Application.persistentDataPath string - which is located somewhere in the Users/Username/AppData/LocalLow/CompanyName/ProjectName/. The SaveFile() method will create a GameData instance which will be filled with the current game data. After serialization the file will be closed.
The LoadFile() method will return if the file is not found. On successful deserialization you will get a GameData instance with the saved variables. You can rewrite the current game data variables with these loaded variables.
Very good and save a lot of time. But every time I try to run the program, it overwrite the existing data. I need to add to the current data not to overwrite it.
Hi sorry but as a newbie, it isn't clear to me how the private variables (currentScore, currentName, currentTimePlayed) can be changed within the rest of the game?
If you call Save/SaveFile from another script, the values will not be changed from 0, Asd, 5.0f, respectively, will they?
This is a good example of what a simple save/load system would start as, do note that it is not recommended to use BinaryFormatter if you're not 100% sure what you might load. See: https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide