For loop variable giving the same end value inside another scope.

I have this code-

    for (int count = 0; count < 3; count++)
            {
                //int k = 3 - count;
                action_list.Add(new Action_time()
                {
                    time = Mathf.Clamp01(count),
                    action = () => { Countdown_text.GetComponent<Animator>().SetTrigger("ease_in");
                        Countdown_text.text = count.ToString(); Debug.Log(count); },
                });
            }

Action_time is just this struct-

public struct Action_time
{
    public float time;
    public UnityAction action;
}

Action_list is a list of Action_time.

The problem is- the text (count value) is always 3 in the action_time constructor, (3 is the number in condition of the loop). I believe that can be because of different scopes.

But- if I uncomment the 3rd line int k = 3 - count (or just k for that matter), and change every other count to k, then the code suddenly works.

Can anyone explain this behavior? Thank you.

EDIT - Just found out that the problem is happening inside the anonymous function’s scope only, NOT in the constructor. If I change the value of time to just count, without the clamp, it does take 0, 1 and then 2.

Hi,
This is a common problem when iterating and creating anonymous functions. UnityAction action is not invoked right away so count variable will be set to the current value in the moment of invoking (in your case 3), but if you cache it just before putting it into an action everything will work fine.

for (int count = 0; count < 3; count++)
             {
                 int chachedCount = count;
                 action_list.Add(new Action_time()
                 {
                     time = Mathf.Clamp01(count),
                     action = () => { Countdown_text.GetComponent<Animator>().SetTrigger("ease_in");
                         Countdown_text.text = chachedCount.ToString(); Debug.Log(chachedCount); },
                 });
             }

For anyone looking for something, this is apparently a C# behavior. Here’s a reference - c# - Why is it bad to use an iteration variable in a lambda expression - Stack Overflow

TLDR- Just use another cache variable. The reason- I believe because it creates a new variable every time using ‘int k = count’.