Navigation

Part 4 - Score Data

Published on 6th November 2018

The setScore method has an optional data argument. In the example above we didn't include it, which is why the data property of the LeaderboardScore object above is also blank.

However, we can use it to save up to 2KB worth of data with the score. This has to be a string.

In Phaser 3.16 if you pass a plain JavaScript object to the setScore method, it will automatically pass it through JSON.stringify. In versions prior to this, you'll need to serialize it first.

Let's save a score with some additional data in Phaser 3.16:

var playerScore = 480;

var roundData = {
    zombies: 349,
    witches: 9,
    bosses: 2,
    bullets: 63320
};

this.leaderboard.setScore(playerScore, roundData);

And in Phaser 3.15, or below:

var playerScore = 480;

var roundData = {
    zombies: 349,
    witches: 9,
    bosses: 2,
    bullets: 63320
};

this.leaderboard.setScore(playerScore, JSON.stringify(roundData));

Here, in our game, we've saved some of the stats that went with the round just played that achieved the high score. In this example, we're keeping track of the total number of baddies that were slain in that round, and how many bullets it took to do so. As this data is round-specific, it's safe to save it with our score, because the next time they play it will be replaced. If we wanted to persist the data regardless we could use Game Stats.

This is what the data looks like when it comes back from the API:

score: 480
scoreFormatted: 480
timestamp: 1542029852
rank: 1
data: {"zombies":349,"witches":9,"bosses":2,"bullets":63320}
playerName: Richard
playerPhotoURL: https://platform-lookaside.fbsbx.com/platform/instantgames/profile_pic.jpg?igpid=XXXXXXXXXXXXXXXX&height=256&width=256&ext=XXXXXXXXXX&hash=AeSAYoU03VQyDZPE
playerID: XXXXXXXXXXXXXXXX

Should we wish to display the data on our leaderboard, we can turn it back to an object again by simply parsing it:

var roundData = JSON.parse(leaderboardScore.data);

Which gives us:

Parsed data

Perfectly suitable, should we wish to display that data in the leaderboard.

Important!

There's one very important thing you need to be aware of when using Score Data: If you don't include the data with your score, it's lost.

For example, take the following:

var playerScore = 400;

var roundData = {
    zombies: 349,
    witches: 9,
    bosses: 2,
    bullets: 63320
};

this.leaderboard.setScore(playerScore, roundData);

// and then, after another round, assuming `playerScore` is a higher number:

this.leaderboard.setScore(playerScore);

Note how we save the roundData with the first call to setScore, but omit it from the second one.

The result is that the data property of the player's score will be empty. If you wish to retain data with a player's score, you have to send that data every single time you save the score, or it'll be lost forever.

In the next part let's get a list of scores back for other players.