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. Dismiss Notice

Button.onClick.AddListener() not saving function arguments correctly

Discussion in 'Scripting' started by phzixis, Dec 29, 2020.

  1. phzixis

    phzixis

    Joined:
    Oct 29, 2017
    Posts:
    2
    Hi I have a code that looks something like this
    Code (CSharp):
    1.  
    2. for(int i = 0; i < currentTabButtons.Count; i++) {
    3.        currentTabButtons[i].onClick.AddListener(()=>SetTab(i));
    4. }
    5.  
    However, they're all using the last value of i instead, which is the number of elements in the currentTabButtons list. (e.g if there are six elements, all buttons would do SetTab(6))

    I tried doing a workaround which involves putting an integer instead of a variable as the argument and it now works as intended.

    What was I doing wrong with the first script?
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
  3. phzixis

    phzixis

    Joined:
    Oct 29, 2017
    Posts:
    2
    Vryken likes this.