3

我正在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#新手,我想知道是否有更好的方法来处理这个问题。

4

1 回答 1

3

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

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

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

And Closing over the loop variable... by Eric Lippert details the behavior and related issues.

于 2012-11-05T22:40:31.670 回答