FarmManager.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Mirror;
  4. using TMPro;
  5. using Unity.VisualScripting;
  6. using UnityEngine;
  7. using UnityEngine.UI;
  8. public class FarmManager : NetworkBehaviour
  9. {
  10. public InventoryManager inventory;
  11. public RectTransform uiPopUp;
  12. public Image fillupImage;
  13. public FarmItem activeItem;
  14. public FarmItem farmingItem;
  15. private void Awake() {
  16. HidePopUp();
  17. uiPopUp.GetComponentInChildren<Button>().onClick.AddListener(Interact);
  18. }
  19. public void ShowPopUp(FarmItem item){
  20. if(farmingItem != null && farmingItem != item){return;}
  21. if(!item.isAvailable && farmingItem != item){return;}
  22. activeItem = item;
  23. uiPopUp.gameObject.SetActive(true);
  24. Vector3 offsetUiPopUp = new Vector3(100, 50, 50);
  25. uiPopUp.position = Camera.main.WorldToScreenPoint(item.transform.position) + offsetUiPopUp;
  26. }
  27. public void HidePopUp(){
  28. uiPopUp.gameObject.SetActive(false);
  29. fillupImage.fillAmount= 0f;
  30. }
  31. void Interact(){
  32. if(activeItem ==null){Debug.LogError("Cant farm an item without having one"); return;}
  33. if(!activeItem.isAvailable){Debug.Log("This item is already being farmed",gameObject); return;}
  34. if(isServer){
  35. activeItem.isAvailable=false;
  36. }else{
  37. CmdDeactivateItem(activeItem.gameObject);
  38. }
  39. farmingItem= activeItem;
  40. StartCoroutine(CoroutineFarm());
  41. }
  42. [Command]
  43. void CmdDeactivateItem(GameObject item){
  44. item.GetComponent<FarmItem>().isAvailable = false;
  45. }
  46. IEnumerator CoroutineFarm(){
  47. float timer =0f;
  48. uiPopUp.GetComponentInChildren<TMP_Text>().text = "Farming";
  49. fillupImage.gameObject.SetActive(true);
  50. while(timer < activeItem.farmingTime){
  51. timer +=Time.deltaTime;
  52. fillupImage.fillAmount = timer / activeItem.farmingTime;
  53. uiPopUp.position = Camera.main.WorldToScreenPoint(activeItem.transform.position);
  54. uiPopUp.gameObject.SetActive(true);
  55. yield return null;
  56. }
  57. HidePopUp();
  58. // FarmingManager.instance.DestroyItem(activeItem.gameObject);
  59. DestroyItem(farmingItem.GetComponent<NetworkIdentity>().netId);
  60. Debug.Log("Requesting to delete this item ", farmingItem);
  61. farmingItem=null;
  62. uiPopUp.GetComponentInChildren<TMP_Text>().text = "Farm";
  63. inventory.AddInvItem(activeItem.lootDrop);
  64. }
  65. void DestroyItem(uint itemNetId){
  66. if(isServer){
  67. FarmingManager.instance.DestroyItemByID(itemNetId);
  68. }else{
  69. CmdDestroyItem(itemNetId);
  70. }
  71. }
  72. [Command]
  73. void CmdDestroyItem(uint itemNetId){
  74. FarmingManager.instance.DestroyItemByID(itemNetId);
  75. }
  76. }