OK, this is a tricky one for me…
I’m trying to add a OnClick listener to my buttons:
int i = 0;
foreach (var optionString in optionsCollection.options)
{
testButtons*.onClick.AddListener(() => SetOption(i));*
i++;
}
But for some reason when I click the button I get this error:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List1[System.Collections.Generic.KeyValuePair
2[System.String,System.String]].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
Yarn.VirtualMachine.m__0 (Int32 selectedOption)
Yarn.Unity.PopulateUI.SetOption (Int32 selectedOption) (at Assets/Scripts/PopulateUI.cs:116)
Yarn.Unity.PopulateUI+c__Iterator5.<>m__0 () (at Assets/Scripts/PopulateUI.cs:93)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args)
…
But if I go like this:
int i = 0;
foreach (var optionString in optionsCollection.options)
{
if (i == 0)
{
testButtons*.onClick.AddListener(() => SetOption(0));*
}else
{
testButtons*.onClick.AddListener(() => SetOption(1));*
}
i++;
}
…it works! My question is why I can’t pas the int i as a parameter of the function SetOption? Why if I hardcode the number it works?
Thank you