Unity - Firebase realtime database - Get my rank in leaderboard

我是研究僧i 提交于 2019-12-02 14:37:53

问题


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);
                }
            }
        });

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!