-1
[SerializeField] List<Button> Buttons;
void Start()
{
    for (int i = 0; i < Buttons.Count; i++)
    {
        Buttons[i].onClick.AddListener(() => DoThing(i));// can't hold i variable
        //when click the each button result is always 3
        // i want 0,1,2
        print(i); // 0,1,2
    }
}
public void DoThing(int value)
{
    print(value);
}

I want to use i as parameter of a button click event action but each button always prints 3. Instead of using i Buttons[i].onClick.AddListener(() => DoThing(2)) is working fine. how use i as parameter

1
  • Captured variables have their lifetime extended by moving them to a generated class. Be careful how you capture them. sharplab.io/… Commented Oct 5, 2022 at 3:38

2 Answers 2

1

In your code, DoThing will capture the variable i (and not its value) and will only get the value of i when you invoke onClick.

Copy the value of a changing variable to the scope where the closure is defined

[SerializeField] List<Button> Buttons;

void Start()
{
    for (int i = 0; i < Buttons.Count; i++)
    {
        var iLocal = i;
        Buttons[i].onClick.AddListener(() => DoThing(iLocal));
    }
}

public void DoThing(int value)
{
    print(value);
}

This fix makes sure that when you get the context where the action was created, iLocal will hold the value corresponding to the index of the button in the list.

Sign up to request clarification or add additional context in comments.

Comments

0

Despite the Answer, i discourage you to use lambda as all to link an event. Why? Because you cannot unsubscribe an anonymous function, you should really link in this way.

https://learn.microsoft.com/it-it/dotnet/standard/delegates-lambdas

[SerializeField] List<Button> Buttons;

void Start()
{
    for (int i = 0; i < Buttons.Count; i++)
    {
        Buttons[i].onClick.AddListener(DoThing);
    }
}

void OnDestroy()
{
    for (int i = 0; i < Buttons.Count; i++)
    {
        Buttons[i].onClick.RemoveListener(DoThing);
    }
}

public void DoThing(int value)
{
    print(value);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.