1. Summarize the problem
The following for cycle keeps on running as i want, but always give me the same clicked button that is "0". It does not give me an error. But by playing the game i can see that it's always the same number.
2. Describe what you've tried
I've tried searching around the internet for people like me. but sadly i couldn't find anything.
3. Show some code
Code that i'm talking about.
int ButtonNum;
public void Start()
{
for (int i = 0; i < ButtonsPage.Length; i )
{
ButtonsPage[i].GetComponent<Button>().onClick.AddListener(delegate { ButtonClicked(ButtonNum); });
}
}
public void ButtonClicked(int i)
{
Debug.Log("Clicked" i);
if (WhichType == "Nose")
{
NoseColor.sprite = NosesColor[i];
NoseOutline.sprite = NosesOutline[i];
}
//ButtonNum will be used to say which one is clicked. Still haven't add it though cause i wanted to fix this problem before
}
CodePudding user response:
You are not modifying ButtonNum
in any way, I assume the goal is to use i
as button number, try changing your code to:
public void Start()
{
for (int i = 0; i < ButtonsPage.Length; i )
{
var temp = i;
ButtonsPage[i].GetComponent<Button>().onClick.AddListener(delegate { ButtonClicked(temp); });
}
}
Temporary variable is required due to how closures work in C#.