Я использую транзакцию, чтобы сохранить счет в таблице лидеров с базой данных Unity3D и RealTime.Моя конечная цель:
- Найти, если
UserID
уже существует в таблице лидеров базы данных. - Если существует
UserID
, чем проверить, является ли НОВЫЙ счет (из игры) ВЫШЕ, чемстарый счет (из базы данных), если это так, удалите старый счет и поместите новый счет. - Если
UserID
НЕ существует, просто добавьте новый счет, если он ВЫШЕ, чем самый низкий показатель всей базы данных.список. В значительной степени то, что он делает сейчас из приведенного ниже примера кода.
Один из способов, о котором я подумал, это отсортировать список по score
, чем я могу пропустить один список целиком.по одному и найдите позицию и оценку userID, затем каким-то образом удалите найденный userID и поместите новую оценку ..
Я пытался отсортировать ее, но, похоже, ничего не помогло сортировке.
Без сомнения, это хитрый.
Код:
TransactionResult AddScoreTransaction(MutableData mutableData) {
List<object> leaders = mutableData.Value as List<object>;
if (leaders == null) {
leaders = new List<object>();
} else if (mutableData.ChildrenCount >= MaxScores) {
// If the current list of scores is greater or equal to our maximum allowed number,
// we see if the new score should be added and remove the lowest existing score.
long minScore = long.MaxValue;
object minVal = null;
foreach (var child in leaders) {
if (!(child is Dictionary<string, object>))
continue;
long childScore = (long)((Dictionary<string, object>)child)["score"];
if (childScore < minScore) {
minScore = childScore;
minVal = child;
}
}
// If the new score is lower than the current minimum, we abort.
if (minScore > score) {
return TransactionResult.Abort();
}
// Otherwise, we remove the current lowest to be replaced with the new score.
leaders.Remove(minVal);
}
// Now we add the new score as a new entry that contains the email address and score.
Dictionary<string, object> newScoreMap = new Dictionary<string, object>();
newScoreMap["score"] = score;
newScoreMap["email"] = email;
newScoreMap["userId"] = userId;
leaders.Add(newScoreMap);
// You must set the Value to indicate data at that location has changed.
mutableData.Value = leaders;
return TransactionResult.Success(mutableData);
}
public void AddScore() {
if (score == 0 || string.IsNullOrEmpty(email)) {
DebugLog("invalid score or email.");
return;
}
DebugLog(String.Format("Attempting to add score {0} {1}", email, score.ToString()));
DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("Leaders").Child("ClassA");
DebugLog("Running Transaction...");
// Use a transaction to ensure that we do not encounter issues with
// simultaneous updates that otherwise might create more than MaxScores top scores.
reference.RunTransaction(AddScoreTransaction)
.ContinueWith(task => {
if (task.Exception != null) {
DebugLog(task.Exception.ToString());
} else if (task.IsCompleted) {
DebugLog("Transaction complete.");
}
});
}