Game Development Reference
In-Depth Information
_users = binary.Deserialize(file) as List.<UserData>;
} catch (error) {
Debug.Log("File not found");
}
}
// C# user:
public void SaveData () {
BinaryFormatter binary = new BinaryFormatter();
FileStream file = new
FileStream(Application.persistentDataPath+"/
highscores.dat", FileMode.Append);
binary.Serialize(file, _users);
}
public void LoadData () {
try {
BinaryFormatter binary = new BinaryFormatter();
FileStream file = new
FileStream(Application.persistentDataPath+"/
highscores.dat", FileMode.Open);
_users = binary.Deserialize(file) as List<UserData>;
} catch (System.IO.FileNotFoundException) {
Debug.Log("File not found");
}
}
Next, we will talk about
PlayerPrefs
, which is basically used to save and load the
data using the key string to identify each piece of data. The values that we can set or get
are
string
,
float
, and
int
. We will use
Player-
Prefs.SetString(Key,Value)
,
PlayerPrefs.SetFloat(Key,Value)
,
and
PlayerPrefs.SetInt(Key,Value)
to store the data. These methods will set
each value based on the key string and save them to the local machine when the user quits
the application. However, we might want to write the data after setting the value. In this
case, we will use the
PlayerPrefs.Save()
function to write the data at the time we
call this method.