我有一个带有排行榜的迷你游戏,使用的是实时Firebase数据库。
从firebase获得用户得分列表之后,我想获得不在列表中的当前用户的分数。
很容易获得当前用户的得分,但是如何知道列表中的排名为OrderByChild(“ score”)。
这是获得排行榜的代码。
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);
}
}
});
答案 0 :(得分:1)
如何知道我的排名
这取决于谁是“我的”。但是,请说您在变量uid
中具有当前用户的UID。然后,您可以通过以下方法确定他们在前10名中的排名:
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");
}
}
答案 1 :(得分:0)
尝试此操作以查找排行榜中的用户等级。这对我有用
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);
}
};