I did the identical factor with a for and foreach loop, or not less than that is what I might wish to consider. However once I use the for loop I get a Index out of vary
exception, whereas all the pieces is ok with the foreach loop. I am creating a list system and the code is meant to put every merchandise you will have in your stock into a list slot. (The visible side)
Right here is the for loop making an attempt to do it:
for (int i = 0; i
ShowInfo(_inventory(i)));
itemUI.Gadgets = _inventory(i);
}
}
and right here is the foreach loop that does “the identical factor”, however would not get an error:
int index = 0;
foreach (Gadgets merchandise in _inventory)
{
GameObject Merchandise = Instantiate(ItemUIPrefab, slots(index).remodel.GetChild(0));
if (Merchandise.TryGetComponent(out ItemUI itemUI))
{
itemUI.DisplayImage.sprite = merchandise.GetItemSO().GetSprite();
itemUI.AmountText.textual content = merchandise.GetItemAmount().ToString();
itemUI.DropOneButton.onClick.AddListener(() => ShowInfo(merchandise));
itemUI.Gadgets = merchandise;
}
index++;
}
The road that produces the error is that this: itemUI.DropOneButton.onClick.AddListener(() => ShowInfo(_inventory(i)));
However I do not see how one can index out of vary. _inventory.Depend
has at all times been lower than slots.Depend
in order that’s not the issue. I am fairly certain the issue is Lambda, as a result of solely once I press the merchandise in stock do I get this error. For some cause it appears to get the unsuitable worth. Am I misunderstanding lambdas right here? Should not every iteration of the loop add a brand new listener to the onClick
utilizing the proper index?
Once I add an area variable: int capturedIndex = i;
and provides that to the lambda: itemUI.DropOneButton.onClick.AddListener(() => ShowInfo(_inventory(capturedIndex)));
the error disappears. Which means the issue is the lambda. I assume I do not 100% perceive how lambdas work.