Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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

Discussion in 'Scripting' started by ibps13, Nov 26, 2016.

  1. ibps13

    ibps13

    Joined:
    Oct 6, 2012
    Posts:
    113
    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...

    Code (CSharp):
    1.        
    2. string[] shots;
    3.         shots = System.IO.Directory.GetFiles (scene.name, "*.png");
    4.  foreach (string item in shots)
    5.         {
    6.             string tmp = item;
    7.            
    8.             Debug.Log ("Found: " + tmp);
    9.             inst = Instantiate(thumbnailPrefab) as GameObject;
    10.             inst.transform.parent = layoutParent.transform;
    11.             inst.transform.localScale = layoutParent.transform.localScale;
    12.             inst.GetComponent<Image>().sprite = SpriteFromPath(tmp);
    13.            
    14.             Button newButton = inst.GetComponent<Button>();      
    15.             newButton.onClick.AddListener(() => ThumbToBig(System.IO.Path.GetFileName(tmp)));
    16.         }        
    any idea ? thanks
     
  2. AndyGainey

    AndyGainey

    Joined:
    Dec 2, 2015
    Posts:
    216
    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.
     
  3. magnite

    magnite

    Joined:
    Dec 12, 2012
    Posts:
    125
    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.
     
  4. ibps13

    ibps13

    Joined:
    Oct 6, 2012
    Posts:
    113
    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...

    :-(