我正在使用GREE c# API在Unity3d中创建一个游戏。我试着在排行榜上为每个人(用户名,分数)运行一个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#新手,所以我想知道是否有更好的方法来处理这个问题。
发布于 2012-11-06 06:40:32
这就是在foreach循环中构造lambda表达式并稍后执行这个lambda表达式时捕获的工作方式。
Fix -声明IScore iscore的本地副本
foreach (IScore eachScore in scores)
{
IScore iscore = eachScore;Eric Lippert的Closing over the loop variable...详细描述了行为和相关问题。
https://stackoverflow.com/questions/13241452
复制相似问题