TransactionResult.Success不更新我的mutableData(Firebase)

时间:2017-12-14 11:40:15

标签: firebase unity3d firebase-realtime-database

我复制了Save Data的代码。

是这样的:

void addScoreToLeaders(string name, int score ,string 
    key,Dictionary<string,object> childUpdates){    
    reference.Child ("leaders").KeepSynced (true);
    reference.Child ("leaders").RunTransaction(mutableData =>{
        List<Dictionary<string,object>> leaders = mutableData.Value as 
                             List<Dictionary<string,object>>;
            if(leaders == null){
                leaders = new List<Dictionary<string,object>>();
            } else if(mutableData.ChildrenCount >= MAX_SCORE){
                int minScore = int.MaxValue;
                Dictionary<string,object> minValue = null;
                foreach(var child in leaders){
                    if(!(child is Dictionary<string,object>)) continue;
                    int childScore = (int)((Dictionary<string,object>)child)
                        ["score"];
                    if(childScore < minScore){
                        minScore = childScore;
                        minValue = child;
                    }
                }
                if(minScore > score){
                    return TransactionResult.Abort ();
                }

                leaders.Remove (minValue);              
            }

            //Add the new high score
            Dictionary<string ,object> newScoreMap = new 
            Dictionary<string,object> ();
            LeaderBoardEntry entry = new LeaderBoardEntry (name, score);
            newScoreMap = entry.ToDictionary ();
            leaders.Add (newScoreMap);
            mutableData.Value = leaders;
            return TransactionResult.Success (mutableData);
        });
    }
好吧,有两件事没有正确发生:

  • TransactionResult.Success(mutableData)不会将新数据存储在该位置

  • 我第一次调用方法

  • 时返回mutableData null

1 个答案:

答案 0 :(得分:0)

[解决]检查代码后,多次测试尝试找到了解决方案。

导致问题的代码的第五行(5):

List<Dictionary<string,object>> leaders = mutableData.Value as 
                         List<Dictionary<string,object>>; 

替换为:

Dictionary<string,object> leaders = mutableData.Value as 
                         Dictionary<string,object>;

因为 mutableData.Value 将此实例中包含的数据作为本机类型返回,我保存了数据,如 Dictionary&lt; .string,object&gt;;