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.