Quick question. What is the best way to save a game score in a mobile device (iOS and Android) using Monogame (example game Flappy Bird score)?
Well there is only 1 way to do it with MonoGame and that is using the IsolatedStorageFile class. All the other approaches you mentioned do not use MonoGame and if you are looking for any Mono solution you should specify so.
Getting an instance of the class. This works the same in MonoGame as it does for XNA.
#if WINDOWS
IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForDomain();
#else
IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
#endif
How to read data from a file.
protected override void OnExiting(object sender, System.EventArgs args)
{
// Save the game state (in this case, the typed text).
IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
// open isolated storage, and write the savefile.
IsolatedStorageFileStream fs = null;
fs = savegameStorage.OpenFile(SAVEFILENAME, System.IO.FileMode.Create);
if (fs != null)
{
// just overwrite the existing info for this example.
fs.WriteByte(gameState); // a single byte
if ((typedText != null) && (typedText.Length > 0))
{
fs.Write(System.Text.Encoding.UTF8.GetBytes(typedText), 0, typedText.Length);
}
fs.Close();
}
base.OnExiting(sender, args);
}
How to write to a file.
protected override void Initialize()
{
gameState = 0;
IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
// open isolated storage, and write the savefile.
if(savegameStorage.FileExists(SAVEFILENAME))
{
IsolatedStorageFileStream fs = null;
try
{
fs = savegameStorage.OpenFile(SAVEFILENAME, System.IO.FileMode.Open);
}
catch (IsolatedStorageException e)
{
// The file couldn't be opened, even though it's there.
// You can use this knowledge to display an error message
// for the user (beyond the scope of this example).
}
if (fs != null)
{
// Reload the last state of the game. This consists of the UI mode
// and any text that was typed on the keyboard input screen.
byte[] saveBytes = new byte[256];
int count = fs.Read(saveBytes, 0, 256);
if (count > 0)
{
// the first byte is the mode, the rest is the string.
gameState = saveBytes[0];
if (count > 1)
{
typedText = System.Text.Encoding.UTF8.GetString(saveBytes, 1, count - 1);
}
fs.Close();
}
}
}
base.Initialize();
}