123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class Inventory
- {
- public event EventHandler OnItemListChanged;
-
- private List<Item> itemList;
- private Item selectedItem;
-
- public Inventory()
- {
- itemList = new List<Item>();
- selectedItem = null;
- }
-
- public void AddItem(Item item)
- {
- bool itemAlreadyInInventory = false;
-
- foreach (Item itemSlot in itemList)
- {
- if (itemSlot.Prefab == item.Prefab)
- {
- itemSlot.Increase(item.Amount);
- itemAlreadyInInventory = true;
- }
- }
-
- if (!itemAlreadyInInventory) itemList.Add(item);
- if (selectedItem == null) selectedItem = item;
-
- OnItemListChanged?.Invoke(this, EventArgs.Empty);
- }
-
- public void RemoveItem(Item item)
- {
- Item itemInInventory = null;
-
- foreach (Item inventoryItem in itemList)
- {
- if (inventoryItem.Prefab == item.Prefab)
- {
- inventoryItem.Decrease(item.Amount);
- itemInInventory = inventoryItem;
- }
- }
-
- if (itemInInventory != null && itemInInventory.IsEmpty())
- {
- if (itemInInventory == selectedItem)
- selectedItem = ItemAfter(selectedItem) ?? ItemBefore(selectedItem);
-
- itemList.Remove(itemInInventory);
- }
-
- OnItemListChanged?.Invoke(this, EventArgs.Empty);
- }
-
- public List<Item> GetItemList()
- {
- return itemList;
- }
-
- public Item GetSelectedItem()
- {
- return selectedItem;
- }
-
- public Item ItemBefore(Item item)
- {
- int idx = itemList.IndexOf(item);
-
- if (idx == -1 || idx == 0) return null;
- return itemList[idx - 1];
- }
-
- public Item ItemAfter(Item item)
- {
- int idx = itemList.IndexOf(item);
-
- if (idx == -1 || idx == itemList.Count) return null;
- return itemList[idx + 1];
- }
-
- public void SelectPreviousItem()
- {
- Item newSelected = ItemBefore(selectedItem);
- if (newSelected == null) return;
-
- OnItemListChanged?.Invoke(this, EventArgs.Empty);
- }
-
- public void SelectNextItem()
- {
- Item newSelected = ItemAfter(selectedItem);
- if (newSelected == null) return;
-
- OnItemListChanged?.Invoke(this, EventArgs.Empty);
- }
- }
|