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#
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.