Simple index loop, but code too bulky?

The goal of the function:
-Find space to add the amount of items inside the inventory
-Return the amount that was unable to be added.

Problem:
In order to change the variables of the struct I have to type out inventory[slotIndex] everytime. I tried doing Resource struct = inventory[slotIndex] but it wasn’t changing the amount or item variable inside.

    public int FindInventorySpace(ResourceStruct currentResource){
        int amountToAdd = currentResource.amount;
        Debug.Log(currentResource.amount);
        for(int slotIndex = 0; slotIndex < inventory.Length; slotIndex++){ //Is there a way to change the attributes or the inventory[slotIndex] without typing it out every time?
            if(inventory[slotIndex].item == currentResource.item ||inventory[slotIndex].item == null){ //If this inventory slot has the existing item or is empty slot
                inventory[slotIndex].item = currentResource.item; //set the inventory slot to the item
                inventory[slotIndex].amount+=amountToAdd; //add the amount.         
                if(inventory[slotIndex].amount > inventory[slotIndex].item.maxAmount){
                    amountToAdd = inventory[slotIndex].amount - inventory[slotIndex].item.maxAmount; //find excess amount
                    inventory[slotIndex].amount-= amountToAdd; //remove excess amount
                }
                else{
                    amountToAdd = 0; //nothing to add left!
                }

                GameManager.Instance.UpdateInventorySlot(slotIndex); //Updates UI for slot
               
                if(amountToAdd == 0){ //return 0
                    break;
                }
            }
        }
        return amountToAdd; //return excess amount if any

Since your resource type is a struct, you are making a copy from inventory[slotIndex]. All changes you make to the variable will not be reflected in your inventory array. You should update inventory after making all your changes.

Resource resource = inventory[slotIndex];

// Make changes to resource here

inventory[slotIndex] = resource;
2 Likes