- Home /
AddListener with argument on multiple Buttons
This has been bugging me too long so I thought I get your advice ... I'm trying to add listeners to many button Components and with arguments.
string[] saveFiles = Directory.GetFiles(Application.persistentDataPath + "/saves/", "*.dat");
GameObject curButton;
string curName;
for(int i = 0; i < saveFiles.Length && i < loadUI.transform.childCount - 1; i++) {
curName = Path.GetFileName(saveFiles[i]);
curName = curName.Substring(0, curName.Length - 4);
curButton = loadUI.transform.GetChild(i + 1).gameObject;
curButton.GetComponent<Button>().onClick.AddListener(delegate { ClickToLoad(curName); });
curButton.GetComponentInChildren<Text>().text = curName;
}
The problem is with the curName variable. If I change the variable it will change for every LIstener. For example if I put this :
curName = "test";
at the end of my code then no matter what button I click(that has a listener assigned with this code) the ClickToLoad()'s argument will always be "test".
A workaround might be declaring variables dynamically but I don't know how to do this either. I'll search more for a solution in delegates and come back
To make it work, as it is, you need to declare the curName variable inside the loop scope
for(//...){
string curName = //...
//...
}
, so it creates a new object on every iteration which the anonymous methods later gonna associated with and take as the argument if it is outside of the loop the object will be the same (string) and will have the the last assigned value.
That is pretty much what happens in the solution you provide with the function.
Cheers.
Answer by IamAnewUser · May 24, 2018 at 04:54 PM
I found a solution (it came to me a minute after I posted this, sigh) It's a hack but it works
I made a method like this
void Try(GameObject curButton, string curNameT)
curButton.GetComponent<Button>().onClick.AddListener(delegate {ClickToLoad(curNameT); });
}
and I replaced this line in line 10 of my question's code
curButton.GetComponent<Button>().onClick.AddListener(delegate {ClickToLoad(curName); });
with this
Try(curButton, curName);
Your answer
![](https://koobas.hobune.stream/wayback/20220612163343im_/https://answers.unity.com/themes/thub/images/avi.jpg)