ItemSlot.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using UnityEngine;
  3. namespace HQFPSWeapons
  4. {
  5. [Serializable]
  6. public class ItemSlot
  7. {
  8. /// <summary>Sent when this slot has changed (e.g. when the item has changed).</summary>
  9. [NonSerialized]
  10. public Message<ItemSlot> Changed = new Message<ItemSlot>();
  11. public bool HasItem { get { return Item != null; } }
  12. public SaveableItem Item { get { return m_Item; } }
  13. private SaveableItem m_Item;
  14. public static implicit operator bool(ItemSlot slot)
  15. {
  16. return slot != null;
  17. }
  18. public void SetItem(SaveableItem item)
  19. {
  20. if(Item)
  21. {
  22. Item.PropertyChanged.RemoveListener(On_PropertyChanged);
  23. Item.StackChanged.RemoveListener(On_StackChanged);
  24. }
  25. m_Item = item;
  26. if(Item)
  27. {
  28. Item.PropertyChanged.AddListener(On_PropertyChanged);
  29. Item.StackChanged.AddListener(On_StackChanged);
  30. }
  31. Changed.Send(this);
  32. }
  33. public int RemoveFromStack(int amount)
  34. {
  35. if(!HasItem)
  36. return 0;
  37. if(amount >= Item.CurrentStackSize)
  38. {
  39. int stackSize = Item.CurrentStackSize;
  40. SetItem(null);
  41. return stackSize;
  42. }
  43. int oldStack = Item.CurrentStackSize;
  44. Item.CurrentStackSize = Mathf.Max(Item.CurrentStackSize - amount, 0);
  45. Changed.Send(this);
  46. return oldStack - Item.CurrentStackSize;
  47. }
  48. public int AddToStack(int amount)
  49. {
  50. if(!HasItem || Item.Data.StackSize <= 1)
  51. return 0;
  52. int oldStackCount = Item.CurrentStackSize;
  53. int surplus = amount + oldStackCount - Item.Data.StackSize;
  54. int currentStackCount = oldStackCount;
  55. if(surplus <= 0)
  56. currentStackCount += amount;
  57. else
  58. currentStackCount = Item.Data.StackSize;
  59. Item.CurrentStackSize = currentStackCount;
  60. return currentStackCount - oldStackCount;
  61. }
  62. private void On_PropertyChanged(ItemProperty.Value propertyValue)
  63. {
  64. Changed.Send(this);
  65. }
  66. private void On_StackChanged()
  67. {
  68. Changed.Send(this);
  69. }
  70. }
  71. }