从动作中调用动作

时间:2012-11-05 22:29:13

标签: c# unity3d gree

我正在Unity3d使用GREE c# API创建游戏。 我试图为排行榜中的每个(用户名,分数)运行Action

代码如下:

public static void LoadBestScoreFromFriends(Action<FriendAndScore> onComplete)
{
    Gree.Leaderboard.LoadScores(LEADERBOARD_ID,
        UnityEngine.SocialPlatforms.UserScope.FriendsOnly,
        UnityEngine.SocialPlatforms.TimeScope.AllTime,
        1,
        100,
        (IScore[] scores) => {

        foreach (IScore iscore in scores)
        {
            // Since the username is needed, a second
            // call to the API must be done
            Gree.User.LoadUser(iscore.userID, 
            (Gree.User guser) => {
                FriendAndScore friend = new FriendAndScore();
                friend.Name = guser.nickname;
                friend.Score = "" + iscore.value;

                // Run the action for every (nickname, score value)
                onComplete(friend);
            }, (string error) => {
                Debug.Log("Couldn't fetch friend! error: " + error);
            });
        }
    });
}

这里的问题是iscore.value它总是一样的。这是foreach的最后一个元素。这是有道理的,因为LoadUser()foreach结束循环后结束。

我想创建第二种方法来进行调用。类似的东西:

private void GetTheUserAndCallTheAction(Action<FriendAndScore> onComplete, string userID, string score)
{
    Gree.User.LoadUser(userID, 
            (Gree.User guser) => {
                FriendAndScore friend = new FriendAndScore();
                friend.Name = guser.nickname;
                friend.Score = score;
                onComplete(friend);
            }, (string error) => {
                Debug.Log("Couldn't fetch friend! error: " + error);
            });
}

由于我是C#新手,我想知道是否有更好的处理方法。

1 个答案:

答案 0 :(得分:3)

按设计 - 这是在foreach循环中构造lambda表达式并稍后执行此lambda时捕获的工作方式。

修复 - 声明IScore iscore的本地副本:

foreach (IScore eachScore in scores)
{
   IScore iscore = eachScore;

Eric Lippert的Closing over the loop variable...详细介绍了行为和相关问题。