ItemWorkspace.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Linq;
  3. using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
  4. using UnityEngine;
  5. namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
  6. {
  7. /// <summary>
  8. /// Abstract item workspace. It can be shop or player inventory. Items can be managed here (selected, moved and so on).
  9. /// </summary>
  10. public abstract class ItemWorkspace : MonoBehaviour
  11. {
  12. public ItemCollection ItemCollection;
  13. public ItemInfo ItemInfo;
  14. public static float SfxVolume = 1;
  15. public Item SelectedItem { get; protected set; }
  16. public abstract void Refresh();
  17. protected void Reset()
  18. {
  19. SelectedItem = null;
  20. ItemInfo.Reset();
  21. }
  22. protected void MoveItem(Item item, ItemContainer from, ItemContainer to, int amount = 1, string currencyId = null)
  23. {
  24. MoveItemSilent(item, from, to, amount);
  25. var moved = to.Items.Last(i => i.Hash == item.Hash);
  26. if (from.Stacked)
  27. {
  28. if (item.Count == 0)
  29. {
  30. SelectedItem = currencyId == null ? moved : from.Items.Single(i => i.Id == currencyId);
  31. }
  32. }
  33. else
  34. {
  35. SelectedItem = from.Items.LastOrDefault(i => i.Hash == item.Hash) ?? moved;
  36. }
  37. Refresh();
  38. from.Refresh(SelectedItem);
  39. to.Refresh(SelectedItem);
  40. }
  41. public void MoveItemSilent(Item item, ItemContainer from, ItemContainer to, int amount = 1)
  42. {
  43. if (item.Count <= 0) throw new ArgumentException("item.Count <= 0");
  44. if (amount <= 0) throw new ArgumentException("amount <= 0");
  45. if (item.Count < amount) throw new ArgumentException("item.Count < amount");
  46. if (to.Stacked)
  47. {
  48. var targets = to.Items.Where(i => i.Hash == item.Hash).ToList();
  49. switch (targets.Count)
  50. {
  51. case 0:
  52. to.Items.Add(new Item(item.Id, item.Modifier, amount));
  53. break;
  54. case 1:
  55. targets[0].Count += amount;
  56. break;
  57. default:
  58. throw new Exception($"Unable to move item silently: {item.Id} ({item.Hash}).");
  59. }
  60. }
  61. else
  62. {
  63. to.Items.Add(new Item(item.Id, item.Modifier, amount));
  64. }
  65. var moved = to.Items.Last(i => i.Hash == item.Hash);
  66. if (from.Stacked)
  67. {
  68. item.Count -= amount;
  69. if (item.Count == 0)
  70. {
  71. from.Items.Remove(item);
  72. }
  73. }
  74. else
  75. {
  76. from.Items.Remove(item);
  77. }
  78. }
  79. }
  80. }