Reputation: 49
I am trying to fetch the daily top scorer's of the game from Game center. I can get All-time top player's score by using this code snippet.
Social.LoadScores ("leaderboard_id",scores => {
if(scores.Length > 0)
{
Debug.Log("Got " + scores.Length + " scores");
string myScores = "Leaderboard:\n";
foreach (IScore score in scores)
myScores += "AllTime" + "\t" + score.userID + " " + score.formattedValue + " " + score.date + "\n"+ " "+score.rank;
Debug.Log(myScores);
}
Well in android this snippet is fetching almost top 25 players for an API call. But in iOS it's only giving top 1 player score and one more thing I couldn't find anything for fetching the daily top score, even though by default its giving all-time top player score. Any suggestions are welcome.
Upvotes: 0
Views: 2347
Reputation: 420
In Unity 5.6 you can do:
void ShowScoresForToday()
{
// OutputField is a Unity text element I'm using to debug this on the device
OutputField.text = "";
var leaderboardID = "leaderboard";
var log = string.Format( "Top score for leaderboard with id: '{0}'", leaderboardID );
Debug.Log( log );
OutputField.text = log;
var leaderboard = Social.CreateLeaderboard();
leaderboard.id = leaderboardID;
leaderboard.timeScope = TimeScope.Today;
leaderboard.LoadScores( success =>
{
var scores = leaderboard.scores;
if ( scores.Length > 0 )
{
foreach ( var score in scores )
{
var logLine = string.Format( "User: '{0}'; Score: {1}; Rank: {2}",
score.userID, score.value, score.rank );
OutputField.text += "\n" + logLine;
}
}
else
{
Debug.LogError( "No scores registered" );
}
} );
}
You have to initialize the Leaderboard object before querying, with the Social.CreateLeaderboard()
Other filters are, hm, limited - https://docs.unity3d.com/ScriptReference/SocialPlatforms.ILeaderboard.html
Would be fun to be able to query specific date ranges, but no.
I would assume that you can't because of how GameCenter itself stores these scores - https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/GameKit_Guide/Achievements/Achievements.html#//apple_ref/doc/uid/TP40008304-CH7-SW30
EDIT: @CharlieSeligman, you asked me about getting the username after you have the userID:
Social.LoadScores( leaderboardID, scores =>
{
var log = string.Format( "There are {0} players in the leaderboard", scores.Length );
Debug.Log( log );
var userIDs = new List<string>();
foreach ( var score in scores )
{
var idLog = string.Format( "User with id '{0}' and scored {1}, rank is {2}",
score, score.value, score.rank );
Debug.Log( idLog );
userIDs.Add( score.userID );
}
Social.LoadUsers( userIDs.Distinct().ToArray(), userProfiles =>
{
var user = userProfiles[0];
var usernameLog = string.Format( "User with id '{0}' is {1}",
user.id, user.userName );
Debug.Log( usernameLog );
} );
} );
Upvotes: 2