Tuesday, January 28, 2025
spot_img

unity – Why is Lambda out of vary when utilizing a for loop however not with a foreach loop?


I did the identical factor with a for and foreach loop, or a minimum of that is what I wish to consider. However after I use the for loop I get an Index out of vary exception, whereas the whole lot is okay with the foreach loop. I’m creating a list system and the code is meant to place every merchandise you have got in your stock in a list slot (The visible side)
Right here is the for loop attempting to do it:

for (int i = 0; i  
         ShowInfo(_inventory[i]));
         itemUI.Objects = _inventory[i];
   }
}

and right here is the foreach loop doing the “similar” factor, however not getting an error:

 int index = 0;
 foreach (Objects 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.Objects = merchandise;
      }
      index++;
 }

The road producing the error is that this one: itemUI.DropOneButton.onClick.AddListener(() => ShowInfo(_inventory[i])); However I do not see how it may be index out of vary. _inventory.Rely has all the time been lower than slots.Rely, so that isn’t the issue. I’m fairly positive the issue is the Lambda, as a result of its solely after I press the Merchandise within the stock I get this error. For some motive it appears to get the flawed worth. Am I understanding lambdas flawed right here? Should not every iteration of the loop add a brand new listener to the onClick utilizing the proper index?

Once I add a neighborhood variable: int capturedIndex = i; and provides that to the lambda: itemUI.DropOneButton.onClick.AddListener(() => ShowInfo(_inventory[capturedIndex])); the error goes away. So which means the issue is the lambda. I suppose I do not 100% perceive how lambdas work.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -spot_img

Latest Articles