Game Development Reference
In-Depth Information
Making your game save and load functions
Using the serialization helper we created earlier and our Save model, we can now imple-
ment our Save and Load functions. So, open up the GameState script from As-
sets\Scripts\Classes and add the following property to mark our save location
on the disk:
static string saveFilePath =
Application.persistentDataPath + "/playerstate.dat";
This just saves us from writing this over and over again. Alternatively, if you are using a
slot-saving system, then this will need to be a list that would also need to be saved (prob-
ably in a PlayerPrefs property). Next, we will add the Save function as follows:
public static void SaveState()
{
try
{
PlayerPrefs.SetString("CurrentLocation",
Application.loadedLevelName);
using (var file = File.Create(saveFilePath))
{
var playerSerializedState =
SerializerHelper.Serialise<PlayerSaveState>
(currentPlayer.GetPlayerSaveState());
file.Write(playerSerializedState,
0, playerSerializedState.Length);
}
}
catch
{
Debug.LogError("Saving data failed");
}
}
So, when we need to save our game, we perform the following actions:
1. Save the player's current location to PlayerPrefs as it is very simple data.
Search WWH ::




Custom Search