CurrentAmmoUi.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.SceneManagement;
  5. using Sirenix.OdinInspector;
  6. using TMPro;
  7. using KairoEngine.Core;
  8. using KairoEngine.UI;
  9. namespace KairoEngine.Inventory
  10. {
  11. // Todo: Refactor Update method to remove CharacterSystem references using the EventSystem for changing values
  12. public class CurrentAmmoUi : MonoBehaviour
  13. {
  14. private ItemContainer playerInventory;
  15. private ItemRef currentItem;
  16. public GameObject canvasParent;
  17. public ItemSlotUi itemSlotUi;
  18. public TextMeshProUGUI textAmmo;
  19. public TextMeshProUGUI textAmmoType;
  20. private string currentScene;
  21. void OnEnable()
  22. {
  23. EventManager.broadcast.StartListening("PlayerShowAmmo", ShowAmmoUI);
  24. GenericEvents.StartListening("PlayerHideAmmo", HideAmmoUI);
  25. UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
  26. }
  27. void OnDisable()
  28. {
  29. EventManager.broadcast.StopListening("PlayerShowAmmo", ShowAmmoUI);
  30. GenericEvents.StopListening("PlayerHideAmmo", HideAmmoUI);
  31. UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded;
  32. }
  33. public void Start()
  34. {
  35. canvasParent.SetActive(false);
  36. }
  37. private void ShowAmmoUI(ItemContainer itemContainer, ItemRef itemRef)
  38. {
  39. this.playerInventory = itemContainer;
  40. this.currentItem = itemRef;
  41. if(itemRef.item.category != ItemType.firearm)
  42. {
  43. canvasParent.SetActive(false);
  44. return;
  45. }
  46. this.canvasParent.SetActive(true);
  47. canvasParent.SetActive(true);
  48. }
  49. private void HideAmmoUI()
  50. {
  51. canvasParent.SetActive(false);
  52. }
  53. private void UpdateAmmo()
  54. {
  55. int totalAmmo;
  56. ItemFirearmRef firearmRef = currentItem as ItemFirearmRef;
  57. ItemRef ammoRef = playerInventory.GetItem(firearmRef.ammoType);
  58. if(ammoRef == null)
  59. {
  60. totalAmmo = 0;
  61. ammoRef = new ItemRef(firearmRef.ammoType, 0);
  62. }
  63. else
  64. {
  65. totalAmmo = ammoRef.quantity;
  66. }
  67. itemSlotUi.Setup(ammoRef, null, null, false);
  68. textAmmoType.text = firearmRef.ammoType.title;
  69. textAmmo.text = firearmRef.ammo + "/" + totalAmmo;
  70. }
  71. public void Update()
  72. {
  73. if(canvasParent.activeSelf) UpdateAmmo();
  74. }
  75. private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
  76. {
  77. currentScene = scene.name;
  78. }
  79. }
  80. }