- Home /
Trying to use a for loop to add items to inventory
Hey there, I'm putting together an inventory system with my limited knowledge of code and not sure how to get my for loop to behave how i want. I need it to check for slots with the same id as the item i pick up and if that dose not work then check for an empty inventory slot (slot with ID of 0).
public void AddItem(int itemID, int amount) { Debug.Log("Search"); for (int i = 0; itemID == slots[i].GetComponent<InvSlot>().activeItem || i > slots.Length; i ++) { if(i > slots.Length) { for (int x = 0; slots[x].GetComponent<InvSlot>().activeItem == 0 || x > slots.Length; x++) { slots[x].GetComponent<InvSlot>().numItemsHeld += 1; slots[x].GetComponent<InvSlot>().activeItem = itemID; } } else slots[i].GetComponent<InvSlot>().numItemsHeld += 1; break; } }
Im not sure if what im saying makes much sense so any help is appreciated XD. Thanks in advanced ;)
Answer by WARdd · Oct 21, 2019 at 01:01 PM
There's no need for complicated for loops, you can just return out of the method when it's finished
public void AddItem(int itemID, int amount) {
for (int i = 0; i < slots.Length; i ++) {
InvSlot slot = slots[i].GetComponent<InvSlot>();
if(slot.activeItem == itemID){
slot.numItemsHeld += amount;
return;
}
}
for (int i = 0; i < slots.Length; i ++) {
InvSlot slot = slots[i].GetComponent<InvSlot>();
if(slot.activeItem == 0){
slot.activeItem = itemID;
slot.numItemsHeld = amount;
return;
}
}
Debug.LogError("No space for given item");
}
Thanks so much for the help, didn't realise i was over complicating it so much XD