- Home /
Passing an int to a function from an onClick event gives the same value on every button.
So I'm calling this to make a bunch of buttons with different resolutions on them and set an onClick event on them that calls the function after it.
for (int x = resString.Length-1; x >= 0; x--)
{
GameObject newButton = (GameObject)Instantiate(resolutionButton);
newButton.transform.SetParent(resolutionPanel);
newButton.transform.localPosition = Vector3.zero;
newButton.transform.localScale = Vector2.one;
newButton.name = x.ToString();
newButton.transform.FindChild("Text").GetComponent<Text>().text = resString[x];
checks[x] = newButton.transform.FindChild("Check").GetComponent<Image>();
checks[x].enabled = (currentRes == x);
int newResInt = x;
Debug.Log(newResInt);
newButton.GetComponent<Button>().onClick.AddListener(
() => { SetResolutionIndex(newResInt, newButton); }
);
}
public void SetResolutionIndex(int theNewIndex, GameObject thisButton)
{
Debug.Log("New Index:" + EventSystem.current.currentInputModule.name);
checkSelectedIndex = theNewIndex;
DoChecks();
}
But I have a problem with the int. It seems that it is using the last set value of "x" on every button (so in this case, 0), even though I am creating a new local integer, newResInt, to pass into the function. I've looked into this issue already, and people have said that should fix it, however, newResInt still seems to be a pointer to x. What am I doing wrong?
try this newResInt = x - 0;
not sure if it will work, but this way the newResInt shouldn't be linking to the x as i suspect it may be.
if it's not that, then it may have to do with the loop itself. i remember hearing that foreach loops sometimes have problems with similar stuff, so maybe it's related. but if you create a function outside of the loop that does all the work inside it (line 2-15) it should fix it, if it's that.
newResInt = x-0 didn't work, but that was a good idea anyway. I thought it might for a second there. HOWEVER, moving everything to a new function and calling that did end up working. Thanks for your help!