gather-and-defend/Assets/Scripts/UnitTree/UpgradePlacementButton.cs
Ader Alisma 01 20a6393888 Revert UI
2024-10-27 11:49:12 -04:00

96 lines
2.8 KiB
C#

using System;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UpgradePlacementButton : MonoBehaviour, IPointerClickHandler
{
private Button _button;
[SerializeField]
private TMP_Text _foodLabel;
[SerializeField]
private TMP_Text _woodLabel;
[SerializeField]
private TMP_Text _rockLabel;
[SerializeField]
private Image _backgroundImage;
[SerializeField]
private Image _unitArt;
[SerializeField]
private GameObject _buttonContainer;
[SerializeField]
private GameObject _prefab;
[SerializeField]
protected UnitCard _unitCardInformation;
private GameObject _unitGameObject;
private Canvas _canvas;
public Button Button => _button;
void Start()
{
_button = GetComponent<Button>();
_button.enabled = true;
}
void Update()
{
if (_unitCardInformation != null)
{
_button.interactable = CanUse();
if (CanUse())
{
_backgroundImage.color = Color.green;
}
else
{
_backgroundImage.color = Color.red;
}
}
}
private bool CanUse()
{
return ResourceManager.Instance.EnoughFor(_unitCardInformation.Rock, _unitCardInformation.Wood, _unitCardInformation.Food);
}
void SetTextFor(TMP_Text label, int value)
{
label.transform.parent.gameObject.SetActive(value > 0);
label.text = "" + value;
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("-----CLICKED----");
if (CanUse())
{
Debug.Log("-----INSTANCIATING----");
//Change parent GameObject
Vector3 instantiatePosition = _unitGameObject.transform.position;
Debug.Log("Upgrade clicked...");
Instantiate(_prefab, instantiatePosition, Quaternion.identity, _canvas.transform);
ResourceManager resourceManager = ResourceManager.Instance;
resourceManager.Remove(_unitCardInformation.Rock, _unitCardInformation.Wood, _unitCardInformation.Food);
Destroy(_unitGameObject);
Destroy(_buttonContainer);
}
}
public void Initialize(UnitUpgrade unitUpgrade, GameObject parentGameObject, Canvas canvas)
{
Debug.Log(unitUpgrade.name);
_unitCardInformation = unitUpgrade.UpgradeUnitCard;
SetTextFor(_foodLabel, _unitCardInformation.Food);
SetTextFor(_woodLabel, _unitCardInformation.Wood);
SetTextFor(_rockLabel, _unitCardInformation.Rock);
_prefab = unitUpgrade.UpgradePrefab;
_unitGameObject = parentGameObject;
_canvas = canvas;
_unitArt.sprite = unitUpgrade.UpgradeCardArt;
}
}