using System; using Core.Economy; using TowerDefense.Level; using TowerDefense.Towers; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace TowerDefense.UI.HUD { /// /// A button controller for spawning towers /// [RequireComponent(typeof(RectTransform))] public class TowerSpawnButton : MonoBehaviour, IDragHandler { /// /// The text attached to the button /// public Text buttonText; public Image towerIcon; public Button buyButton; public Image energyIcon; public Color energyDefaultColor; public Color energyInvalidColor; /// /// Fires when the button is tapped /// public event Action buttonTapped; /// /// Fires when the pointer is outside of the button bounds /// and still down /// public event Action draggedOff; /// /// The tower controller that defines the button /// Tower m_Tower; /// /// Cached reference to level currency /// Currency m_Currency; /// /// The attached rect transform /// RectTransform m_RectTransform; /// /// Checks if the pointer is out of bounds /// and then fires the draggedOff event /// public virtual void OnDrag(PointerEventData eventData) { if (!RectTransformUtility.RectangleContainsScreenPoint(m_RectTransform, eventData.position)) { if (draggedOff != null) { draggedOff(m_Tower); } } } /// /// Define the button information for the tower /// /// /// The tower to initialize the button with /// public void InitializeButton(Tower towerData) { m_Tower = towerData; if (towerData.levels.Length > 0) { TowerLevel firstTower = towerData.levels[0]; } else { Debug.LogWarning("[Tower Spawn Button] No level data for tower"); } if (LevelManager.instanceExists) { m_Currency = LevelManager.instance.currency; m_Currency.currencyChanged += UpdateButton; } else { Debug.LogWarning("[Tower Spawn Button] No level manager to get currency object"); } UpdateButton(); } /// /// Cache the rect transform /// protected virtual void Awake() { m_RectTransform = (RectTransform) transform; } /// /// Unsubscribe from events /// protected virtual void OnDestroy() { if (m_Currency != null) { m_Currency.currencyChanged -= UpdateButton; } } /// /// The click for when the button is tapped /// public void OnClick() { if (buttonTapped != null) { buttonTapped(m_Tower); } } /// /// Update the button's button state based on cost /// void UpdateButton() { if (m_Currency == null) { return; } // // Enable button // if (m_Currency.CanAfford(m_Tower.purchaseCost) && !buyButton.interactable) // { // buyButton.interactable = true; // energyIcon.color = energyDefaultColor; // } // else if (!m_Currency.CanAfford(m_Tower.purchaseCost) && buyButton.interactable) // { // buyButton.interactable = false; // energyIcon.color = energyInvalidColor; // } } } }