0

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);
                }
            }
        });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Carson Vo
  • 476
  • 6
  • 20

2 Answers2

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");
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for your answer. I mean the current user was out of the top 10. And I would like to know the rank of the current user. – Carson Vo Oct 24 '18 at 04:56
  • 2
    There is no built-in query operator to get the index of an item. You'll either need to load enough items to find the current user, or keep the rank of the user in a separate property in the database and update it all the time. See https://stackoverflow.com/questions/46720997/leaderboard-ranking-with-firebase, https://stackoverflow.com/questions/48128031/getting-rank-of-user-from-firebase-database-in-android – Frank van Puffelen Oct 24 '18 at 06:13
0

Try this for find user-rank in leaderboard.this works for me

sample image after code

    email_arrayList = new ArrayList();

    var currentUser = FirebaseAuth.DefaultInstance.CurrentUser;

    int rank = 0;
     playerId = currentUser.UserId;
     Debug.Log(playerId);

    FirebaseDatabase.DefaultInstance.GetReference("users").ValueChanged += FirebaseSaveLoadScript_ValueChanged;

    FirebaseDatabase.DefaultInstance
      .GetReference("users").OrderByChild("userScore")
      .ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
          if (e2.DatabaseError != null)
          {
              Debug.LogError(e2.DatabaseError.Message);
              return;
          }
          Debug.Log("Received values for Leaders.");
          string title = leaderBoard[0].ToString();
          leaderBoard.Clear();
          leaderBoard.Add(title);
          if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0)
          {
              foreach (var childSnapshot in e2.Snapshot.Children)
              {
                  if (childSnapshot.Child("userScore") == null
                || childSnapshot.Child("userScore").Value == null)
                  {
                      Debug.LogError("Bad data in sample.  Did you forget to call SetEditorDatabaseUrl with your project id?");
                      break;
                  }
                  else
                  {
                      Debug.Log("Leaders entry : " +
                    childSnapshot.Child("userEmail").Value.ToString() + " - " +
                    childSnapshot.Child("userScore").Value.ToString());

                      email_arrayList.Add(childSnapshot.Child("userEmail").Value.ToString());

                      leaderBoard.Insert(1, childSnapshot.Child("userScore").Value.ToString()
                    + "  " + childSnapshot.Child("userEmail").Value.ToString());

                      displayScores.text = "";
                      foreach (string item in leaderBoard)
                      {
                          displayScores.text += "\n" + item;

                      }
                  }

              }
          }

          email_arrayList.Reverse();
          foreach (string obj in email_arrayList)
          {
              rank++;
              if (obj == currentUser.Email)
              {
                  int rank_final = rank;
                  Debug.Log("I'm number " + rank_final + " in the rankings");
                  userRank.text = "Your Rank is " + rank_final;
                  rank = 0;
                  break;
              }

              Debug.Log(obj);

          }

      };