Création d'un petit party-game anonyme de Build + Bagar sous Unity
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Inventory.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public class Inventory
  6. {
  7. public event EventHandler OnItemListChanged;
  8. private List<Item> itemList;
  9. private Item selectedItem;
  10. public Inventory()
  11. {
  12. itemList = new List<Item>();
  13. selectedItem = null;
  14. }
  15. public void AddItem(Item item)
  16. {
  17. bool itemAlreadyInInventory = false;
  18. foreach (Item itemSlot in itemList)
  19. {
  20. if (itemSlot.Prefab == item.Prefab)
  21. {
  22. itemSlot.Increase(item.Amount);
  23. itemAlreadyInInventory = true;
  24. }
  25. }
  26. if (!itemAlreadyInInventory) itemList.Add(item);
  27. if (selectedItem == null) selectedItem = item;
  28. OnItemListChanged?.Invoke(this, EventArgs.Empty);
  29. }
  30. public void RemoveItem(Item item)
  31. {
  32. Item itemInInventory = null;
  33. foreach (Item inventoryItem in itemList)
  34. {
  35. if (inventoryItem.Prefab == item.Prefab)
  36. {
  37. inventoryItem.Decrease(item.Amount);
  38. itemInInventory = inventoryItem;
  39. }
  40. }
  41. if (itemInInventory != null && itemInInventory.IsEmpty())
  42. {
  43. if (itemInInventory == selectedItem)
  44. selectedItem = ItemAfter(selectedItem) ?? ItemBefore(selectedItem);
  45. itemList.Remove(itemInInventory);
  46. }
  47. OnItemListChanged?.Invoke(this, EventArgs.Empty);
  48. }
  49. public List<Item> GetItemList()
  50. {
  51. return itemList;
  52. }
  53. public Item GetSelectedItem()
  54. {
  55. return selectedItem;
  56. }
  57. public Item ItemBefore(Item item)
  58. {
  59. int idx = itemList.IndexOf(item);
  60. if (idx == -1 || idx == 0) return null;
  61. return itemList[idx - 1];
  62. }
  63. public Item ItemAfter(Item item)
  64. {
  65. int idx = itemList.IndexOf(item);
  66. if (idx == -1 || idx == itemList.Count) return null;
  67. return itemList[idx + 1];
  68. }
  69. public void SelectPreviousItem()
  70. {
  71. Item newSelected = ItemBefore(selectedItem);
  72. if (newSelected == null) return;
  73. OnItemListChanged?.Invoke(this, EventArgs.Empty);
  74. }
  75. public void SelectNextItem()
  76. {
  77. Item newSelected = ItemAfter(selectedItem);
  78. if (newSelected == null) return;
  79. OnItemListChanged?.Invoke(this, EventArgs.Empty);
  80. }
  81. }