- Home /
Problem is not reproducible or outdated
Assigning a function with a parameter to buttons in for loop with a temp variable
Hello, I am trying to assign a function with a parameter to buttons that I create in for loop. I use a delegate to assign it and I make sure to pass a local temp variable as a parameter. For some when I click the button it still calls the function with the reference to the last value of tempint. I have no idea why as I saw countless posts about people using the same thing and it works for them.
void Start ()
{
float activeArea = Screen.height * 0.75f ;
print(activeArea);
float buttonDistances = (activeArea) / AudioStreamer.Instance.numberOfStates;
float currentdist = (activeArea * 0.5f) - buttonDistances;
float buttonheight = buttonDistances * 0.8f;
for (int i = 0; i < AudioStreamer.Instance.numberOfStates; i++)
{
GameObject newbutton = Instantiate(button);
newbutton.transform.SetParent(gameObject.transform, false);
newbutton.transform.localPosition = new Vector3(0, currentdist, 0);
Button mybutton = newbutton.GetComponent<Button>();
mybutton.image.rectTransform.sizeDelta = new Vector2(400, buttonheight);
int tempint = i;
mybutton.onClick.AddListener(delegate { CmdSetMusicTo(tempint); }); //<----- This is not working proeprly
Text mytext = newbutton.GetComponentInChildren<Text>();
mytext.text = MusicFromManager.Instance.l_from_MusicContainers[i].stateName.text;
currentdist -= buttonDistances;
l_control_Buttons.Add(mybutton);
}
public void CmdSetMusicTo(int statenum)
{
AudioStreamer.Instance.func_SetMusicState(statenum);
}
Help is much appricated, thanks
Is that really your actual code? $$anonymous$$eep in $$anonymous$$d that you can't use local temp variables inside a coroutine when you deal with closures as all local variables becomes member variables of the coroutine statemachine object.
The code you've posted should work just fine. So make sure this is really your actual code and tell us what you did to debug the problem. Where did you add Debug.Log statements and what did they return?.
Yes that is my actual code. I do not use it in a coroutine I use it in the Start() function. I debugged with attaching a Unity debugger to VS and seeing all the correct variables being passed in the delegate. I also printed all the values of the tempint before it is assigned and showed it correctly
Answer by Darken · Oct 07, 2017 at 12:42 AM
Found the problem, it was passing the correct number but the function inside the Audio Streamer was not handling it correctly. Was looking in the wrong Class.
Follow this Question
Related Questions
Unity UI dynamic Buttons 4 Answers
While loop not updating 1 Answer
Move Button OnClick listeners to another button 3 Answers
Runtime Click Listener Addition 0 Answers
add delegate to toggle in unity 4.6 UI 2 Answers