- Home /
Removing Same Item Multiple Times From List
So, I've been making a building game, but now what I want to do is, whenever I build something (wall/floor/stairs) I want to remove the required "Wood" from inventory, So for example, if I build a floor, I need 2 Wood, and if I have 2 or more Wood in inventory, I want to make it so that it removes 2 Wood from inventory at the same time, but in a cleaner script. Dont want to be doing 'list.Remove(wood); list.Remove(Wood); It's hard to explain, but feel free to ask any more questions about it!!
public Inventory inv;
public Item material;
...
public void Build()
{
//gets object with the script 'buildghost' as it requires to know if the object is able to be built or not (it checks this through triggers)
BuildGhost PO = assetVisual.GetComponent<BuildGhost>();
if (enoughResources)
{
if (PO.IsBuildable)
{
//Builds object if current object is enabled.
Instantiate(currentAsset.AssetObject, currentPos, Quaternion.Euler(currentRot));
inv.items.Remove(material);
inv.items.Remove(material);
}
}
}
Answer by maross334 · Apr 16 at 03:18 AM
for(int i = 0; i < requiredWood; i++){
inv.items.Remove(wood);
}
Note that you should validate that the player actually has enough wood. I would consider using a dictionary that uses the material as the key, and the number the player has as a value. ex:
Dictionary<material, int> playerInventory = new Dictionary<material, int>();
if(playerInventory.ContainsKey(wood) && playerInventory[wood] > requiredWood){
playerInventory[wood] -= wood;
//instantiate go here
}
Make sure to check if it contains the key before checking if there is enough. It throws errors if you try to access a value that does not have an associated key.
Removing required amount of wood worked like a charm! Although I already had a dictionary checking for wood in inventory already, i still couldn't figure out how your validation works, because mine is more complex then yours (wish mine looked as cleaner as yours)
If my answer helped, can you mark me as the best answer? Thanks :) always glad to help
Your answer
![](https://koobas.hobune.stream/wayback/20220613055436im_/https://answers.unity.com/themes/thub/images/avi.jpg)