I am making a simple 2d game for WP in monogame/xna and am at a point where I want to save data. I have created a method to serialize the data (index, counter and percentage counter) to an isolated storage file in xml format. There is also a subsequent method to deserialize the file. My question is simply, what point is best to save the game, because at the moment I save when the a pause screen is loaded over the gameplay screen - However, this wont save the data if the player exits the app. I am certain I am saving in a silly place. Hence, I am wondering what the common practice is for saving? Any help/advice would be greatly appreciated.
Here is my save method:
public void SaveData()
{
const string filename = "data.vision";
#if WINDOWS_PHONE
IsolatedStorageFile dataFile = IsolatedStorageFile.GetUserStoreForApplication();
#else
IsolatedStorageFile dataFile = IsolatedStorageFile.GetUserStoreForDomain();
#endif
try
{
// Create an isolated storage stream and initialize it as null.
IsolatedStorageFileStream isolatedFileStream = null;
// Check the data file already exists.
if (dataFile.FileExists(filename))
{
// Open the file using the established file stream.
using (isolatedFileStream = dataFile.OpenFile(filename, FileMode.Open, FileAccess.ReadWrite))
{
// Read the data from the file.
XmlSerializer serializer = new XmlSerializer(typeof(Data));
// Store the deserialized data object.
Data savedData = (Data)serializer.Deserialize(isolatedFileStream);
// Loop through the LevelData objects within savedData.
for (int i = 0; i < savedData.Levels.Count; i++)
{
// Get the LevelData object in question.
LevelData levelData = savedData.Levels[i];
// Check to see if the index of the levelData object corresponds to the active level index.
if (levelData.Index == mLevelIndex)
{
// Increment the stored attempts by the current attempt counter.
levelData.Attempts += mLevel.AttemptCounter;
// Check if the stored completion percentage is less that the current percentage.
if (levelData.PercentComplete < mLevel.PercentComplete)
levelData.PercentComplete = mLevel.PercentComplete;
//System.Diagnostics.Debug.WriteLine("new attempts " + levelData.PercentComplete);
}
// Update the level data element within the saved date.
savedData.Levels[i] = levelData;
}
// Set the position to the begining of the file.
isolatedFileStream.Seek(0, SeekOrigin.Begin);
// Serialize the new data object.
serializer.Serialize(isolatedFileStream, savedData);
// Set the length of the file.
isolatedFileStream.SetLength(isolatedFileStream.Position);
}
}
}