[SOLVED]Temporary variable inside of the foreach block not work

Hi,

Try to add onclick event to instatiated button at runtimr but still not work, it’s always the last value, I have added variable inside of the lambda…

string[] shots;
        shots = System.IO.Directory.GetFiles (scene.name, "*.png");
 foreach (string item in shots)
        {
            string tmp = item;
           
            Debug.Log ("Found: " + tmp);
            inst = Instantiate(thumbnailPrefab) as GameObject;
            inst.transform.parent = layoutParent.transform;
            inst.transform.localScale = layoutParent.transform.localScale;
            inst.GetComponent<Image>().sprite = SpriteFromPath(tmp);
           
            Button newButton = inst.GetComponent<Button>();       
            newButton.onClick.AddListener(() => ThumbToBig(System.IO.Path.GetFileName(tmp)));
        }

any idea ? thanks

I just tested with and without the local tmp variable in both a normal Windows C# project and a Unity 5.4 project. In normal C#, it looks like it captures the variable by value when using either the loop variable or a local temporary variable. In Unity 5.4, it captures the loop variable by value, but it captures the local temporary variable by reference!

Edit: I was reading my Unity 5.4 test backward. In my simplified case, it works with the local temp, but not with the loop variable. Not sure what is different between your case and mine.

I would suggest removing the GetFileName call and putting it outside of the lambda expression. It may be being passed by reference to that function call before its value is given to the lambda expression. But I’m not sure.

Thanks for feedback, just found the problem and is not the foreach problem… but my function to save the files name…
always register the same name…

:frowning: