Added survival mechanic that consumes inventory items if needed.
This commit is contained in:
@@ -45,12 +45,48 @@ public class Inventory
|
||||
|
||||
public void RemoveItem(string id, int amount)
|
||||
{
|
||||
Item item = items.Find(x => x.data.Id == id && x.currentAmount >= amount);
|
||||
if (item != null)
|
||||
TryRemoveItem(id, amount);
|
||||
}
|
||||
|
||||
public bool TryRemoveItem(string id, int amount)
|
||||
{
|
||||
if (GetItemAmount(id) < amount)
|
||||
{
|
||||
item.currentAmount -= amount;
|
||||
NotifyInventoryChanged();
|
||||
return false;
|
||||
}
|
||||
|
||||
int remainingAmount = amount;
|
||||
for (int i = items.Count - 1; i >= 0 && remainingAmount > 0; i--)
|
||||
{
|
||||
Item item = items[i];
|
||||
if (item.data.Id != id) continue;
|
||||
|
||||
int removedAmount = Math.Min(item.currentAmount, remainingAmount);
|
||||
item.currentAmount -= removedAmount;
|
||||
remainingAmount -= removedAmount;
|
||||
|
||||
if (item.currentAmount <= 0)
|
||||
{
|
||||
items.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
NotifyInventoryChanged();
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetItemAmount(string id)
|
||||
{
|
||||
int amount = 0;
|
||||
foreach (Item item in items)
|
||||
{
|
||||
if (item.data.Id == id)
|
||||
{
|
||||
amount += item.currentAmount;
|
||||
}
|
||||
}
|
||||
|
||||
return amount;
|
||||
}
|
||||
|
||||
private void NotifyInventoryChanged()
|
||||
|
||||
Reference in New Issue
Block a user