How can I check a players inventory for an item, get the amount of that item in that inventory and remove a certain amount of it from that inventory?
Getting player inventory and remove a certain amount of an item?
////Check if player has item/////
private bool CanRemoveResource(Player player, string resource, int amount)
{
// Check player's inventory
var inventory = player.CurrentCharacter.Entity.GetContainerOfType(CollectionTypes.Inventory);
// Check how much the player has
var foundAmount = 0;
foreach (var item in inventory.Contents.Where(item => item != null))
{
if (item.Name == resource)
{
foundAmount = foundAmount + item.StackAmount;
}
}
if (foundAmount >= amount) return true;
return false;
}
/////removing items from player/////
public void RemoveItemsFromInventory(Player player, string resource, int amount)
{
ItemCollection inventory = player.GetInventory().Contents;
int removeAmount = 0;
int amountRemaining = amount;
foreach (InvGameItemStack item in inventory.Where(item => item != null))
{
if (item.Name != resource) continue;
removeAmount = amountRemaining;
if (item.StackAmount < removeAmount) removeAmount = item.StackAmount;
inventory.SplitItem(item, removeAmount);
amountRemaining = amountRemaining - removeAmount;
}
}