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

问题描述 投票:0回答:1

我复制了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
firebase unity3d firebase-realtime-database
1个回答
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 <.string,object>;这样的数据。

© www.soinside.com 2019 - 2024. All rights reserved.