Saving and Loading Game State

Welcome to the Facebook Instant Games SDK Tutorials. This series of tutorials covers many aspects of using the Facebook Instant Games SDK.

In this tutorial we will look the important process of saving and loading the players game state using the Facebook Instant Games SDK. The beauty of the IG player data system is that it persists across platforms, so a player can pick up where they left off on any device.

Saving Player Data

You can save player state data by calling FBInstant.player.setDataAsync(data_object) passing it an object of data to save to the key value store. Note that this is an async function so saving will not occur immediately and it can fail. Lets take a look at how to save some basic player data:
[sourcecode language=”js”]
var data_object = {
somedata1 : 10,
somedata2 : "Hello",
};
FBInstant.player.setDataAsync(data_object)
.then(function() {
// Data saved successfully
}).catch(function(error) {
// Data save failed
});
[/sourcecode]

Getting Player Data

You can retrieve the players data by calling FBInstant.player.getDataAsync(property_array), specifying which keys you want to retrieve. Note that this is an async function so loading will not occur immediately and it can fail. Lets take a look at how to load some basic player data:
[sourcecode language=”js”]
FBInstant.player.getDataAsync([“somedata1”, “somedata2”])
.then(function(data) {
// Data loaded successfully
if (data !== undefined && data.somedata1 !== undefined) // Check data exists
{
console.log(data.somedata1);
}
}).catch(function(error) {
// Data load failed
});
[/sourcecode]
Note that you should check that the data you are requesting actually exists as it may not have been written yet (for example, when the player runs the game for the first time).

In my experience you seem to be able to write to the players data storage as often as you like. I believe that the data is not actually sent to the server until the game exits or possibly at regular intervals.

You can save a maximum of 1MB of data per user.

Leave a Reply