- Home /
Array Overflow Problem
So I was making my inventory. And I want the user to be able to move items. I have a 4x6 grid of buttons all assigned in a table:
PhysGUI = InvPanel.GetComponentsInChildren<Text> ();
That's fine, when I try to add listeners to them, all of them give me 24. The assignment is in a for loop:
for (int i = 0; i < PhysGUI.Length; i++) {
Debug.Log (i.ToString ());
PhysGUI[i].gameObject.GetComponentInParent<Button> ().onClick.AddListener (delegate {
ButtonPress (i);
});
}
ButtonPress() prints out the number that comes up immedeately, and no matter which button I push, I get 24.
Is there something I'm missing? Or what?
Answer by anmolmahatpurkar · Sep 09, 2015 at 07:05 PM
Try this:
for (int i = 0; i < PhysGUI.Length; i++) {
Debug.Log (i.ToString ());
int iValue = i;
PhysGUI[iValue].gameObject.GetComponentInParent<Button> ().onClick.AddListener (delegate {
ButtonPress (iValue);
});
}
i is a local variable on the "for" block of code. Its value increments to the last number of the for loop long before you press the button. The value is PhysGUI.Length in this case, so when you press any button, it displays the last value.
Your answer
Follow this Question
Related Questions
Error CS0029 Help? (Screenshot of Exact Error) 1 Answer
Affect every object in array. 1 Answer
Multiple Cars not working 1 Answer
Inventory system using an array... 3 Answers
Distribute terrain in zones 3 Answers