Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / UI / Inventory / AmountInserter.cs
  1. using TMPro;
  2. using UnityEngine;
  3. using MyCollections.Interfaces;
  4. public class AmountInserter : MonoBehaviour
  5. {
  6. [SerializeField] private TMP_InputField inputField;
  7. [SerializeField] private InputType inputType;
  8. [SerializeField] private int amount;
  9. [SerializeField] private int index;
  10. private GameObject receiver;
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. inputField.lineType = TMP_InputField.LineType.SingleLine;
  15. inputField.onValueChanged.AddListener(delegate
  16. {
  17. Validate();
  18. });
  19. inputField.onSubmit.AddListener(delegate { Submit(); });
  20. }
  21. // Update is called once per frame
  22. void Update()
  23. {
  24. //if (Input.GetKeyDown(KeyCode.Return))
  25. //{
  26. // Submit();
  27. //}
  28. //Debug.Log("Amount: " + amount);
  29. }
  30. public void Init(GameObject obj, int limitAmount, int index)
  31. {
  32. amount = limitAmount;
  33. receiver = obj;
  34. this.index = index;
  35. }
  36. private void Submit()
  37. {
  38. if (receiver.TryGetComponent(out IReceiver<int, int> destination))
  39. {
  40. switch (inputType)
  41. {
  42. case InputType.Numbers:
  43. if (int.TryParse(inputField.text, out int result))
  44. {
  45. destination.Receive(result, index);
  46. Destroy(gameObject);
  47. }
  48. break;
  49. }
  50. }
  51. }
  52. private void Validate()
  53. {
  54. string text = inputField.text;
  55. if (int.TryParse(text, out int result))
  56. {
  57. if (result > amount)
  58. {
  59. inputField.text = amount.ToString();
  60. return;
  61. }
  62. inputField.text = result.ToString();
  63. return;
  64. }
  65. Debug.LogError("Couldn't Parse!");
  66. }
  67. public void ClosePanel() => Destroy(gameObject);
  68. }
  69. public enum InputType
  70. {
  71. Text,
  72. Numbers
  73. }