0

I'm using Unity's scriptable objects to create inventory items and inventory containers. It's worked out very well so far but I've been unsuccessful in finding a method to remove an inventory item from the container list completely.

I have been able to add inventory items to the container and adjust the quantities, but I really would like to be able to remove the S.O. inventory item off the list completely.


public class Container : ScriptableObject
{
    public List<InventoryStack> Contents = new List<InventoryStack>();

    //...
  
    public void AdjustQuantity(BaseObject nameIn, int quantity)
    {
        bool hasItem = false;

        for (int i = 0; i < Contents.Count; i++)
        {
            if (Contents[i].name == nameIn)
            {
                Contents[i].AddAmount(quantity);
          
                if (Contents[i].GetQuantity() == 0)
                {

                    // Trying to remove the InventoryStack from List
                    // method 1 -- is a syntax error
                    // [M1] Contents.Remove(InventoryStack(nameIn));
                    // method 2 -- sets quanity of 1 to -1 lol?
                    // [M2] Contents.RemoveAt(i);
                    
                    break;
                }
           
                hasItem = true;
                break;
            }
        }
        if (!hasItem)
        {
            Contents.Add(new InventoryStack(nameIn, quantity));
        }
    }

I tried writing the functionality in several ways but in this function it gives a good contrast to the how I'm adding objects and adjusting numbers.

This function should search the contents of the container and if it already has one it should just add or subtract the number, if the result is zero it SHOULD remove the item from the container, otherwise if the item didn't exist previously it should add the item to the container. Only the attempt to remove the object from the container isn't working.

example of container, last inventory item should be removed

  • when you want to remove items from a list, you should either temporairly copy the list and remove the items in the copy while iterating the original, or iterate iin reverse order. – MakePeaceGreatAgain Nov 09 '22 at 11:09

0 Answers0