I have a mini-game with a leaderboard using firebase database realtime.
After I got list of user-score from firebase, I would like to get the score of the current user who was out of the list.
It's easy to get the score of the current user but how to know the rank in list which was OrderByChild("score").
This is the code to get the leaderboard.
List<UserScore> leaderBoard = new List<UserScore>();
FirebaseDatabase.DefaultInstance
.GetReference("user-scores")
.OrderByChild("score")
.LimitToLast(10)
.GetValueAsync()
.ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.Log("Fail To Load");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
foreach (DataSnapshot h in snapshot.Children)
{
UserScore userScore = new UserScore(h.Child("uid").Value.ToString(), h.Child("name").Value.ToString(), h.Child("photo").Value.ToString(),int.Parse(h.Child("score").Value.ToString()));
leaderBoard.Add(userScore);
}
}
});
how to know my rank
That depends a bit on who "my" is. But say you have the UID of the current user in a variable uid
. You can then determine their rank in this top 10 with:
int rank = 0;
foreach (DataSnapshot h in snapshot.Children)
{
rank = rank + 1;
UserScore userScore = new UserScore(
h.Child("uid").Value.ToString(),
h.Child("name").Value.ToString(),
h.Child("photo").Value.ToString(),
int.Parse(h.Child("score").Value.ToString()));
leaderBoard.Add(userScore);
if (h.Child("uid").Value.ToString() == uid) {
Debug.Log("I'm number "+rank+" in the rankings");
}
}
来源:https://stackoverflow.com/questions/52961118/unity-firebase-realtime-database-get-my-rank-in-leaderboard