2

I have the following call:

GameSmart.HighScores.Load(Order.Descending, (HighScoresLoadedResponse response) => {
    foreach(Score score in response.data.scores){
        GameSmart.GetImage(score.avatar, (Sprite sprite) => {
            print(score.score);
        });
    }
});

In my foreach, can I somehow pass the value of score to the anonymous function to be used when the anonymous function gets executed? What I have now always displays the last value in the Score array every time the anonymous function executes.

Here is the definition of GetImage

public static void GetImage(string url, Action<Sprite> onComplete = null)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

2 Answers2

3

I can't test it right now, but I believe this should work:

GameSmart.HighScores.Load(Order.Descending, (HighScoresLoadedResponse response) => {
    foreach(Score score in response.data.scores){
        var scoreRef = score;
        GameSmart.GetImage(score.avatar, (Sprite sprite) => {
            print(scoreRef.score);
        });
    }
});
Katana314
  • 8,429
  • 2
  • 28
  • 36
  • that looks like it works. Why do I have to assign it to a new variable? – Get Off My Lawn Mar 24 '16 at 20:40
  • 2
    the `foreach` shorthand hides the fact that it's declaring `Score score` outside of the loop. With a variable *inside* the loop, the closures each treat it as a different variable because the scope is restarted each time through. I think a better explanation is here: http://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp – Katana314 Mar 24 '16 at 20:42
  • 1
    @GetOffMyLawn https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/ – spender Mar 24 '16 at 20:43
1

You need to copy score to a local variable inside the foreach loop in C# versions before 5.0 . See this question for an explanation of the design change Is there a reason for C#'s reuse of the variable in a foreach?

Community
  • 1
  • 1
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46