Newer
Older
Hierarchical-Task-Network-Unity-3D / Assets / Scripts / UI / UIController.cs
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UIElements;

public class UIController : MonoBehaviour
{
    [Header("References: ")]
    [SerializeField] private TextMeshProUGUI revenueAmount;
    [SerializeField] private UIDocument uiDocument;

    [Header("Layer Buttons: ")]
    [SerializeField] private UnityEngine.UI.Button upperLayerButton;
    [SerializeField] private UnityEngine.UI.Button downLayerButton;

    public UnityAction<LayerLevelAction> onLayerChange;
    private float lastRevenueAmount;

    void Start()
    {
        ShopManager.Instance.onPaymentReceived += HandleRevenueChanged;

        if (upperLayerButton != null)
        {
            upperLayerButton.onClick.AddListener(() =>
            {
                onLayerChange?.Invoke(LayerLevelAction.Increment);
            });
        }

        if (downLayerButton != null)
        {
            downLayerButton.onClick.AddListener(() =>
            {
                onLayerChange?.Invoke(LayerLevelAction.Decrement);
            });
        }
    }

    // This method runs when revenue changes
    private void HandleRevenueChanged(float newAmount)
    {
        StartCoroutine(UpdateRevenue(lastRevenueAmount, newAmount));
        lastRevenueAmount = newAmount;
    }

    private IEnumerator UpdateRevenue(float from, float to)
    {
        float duration = 0.5f; // Duration of the animation in seconds
        float elapsed = 0f;

        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float t = Mathf.Clamp01(elapsed / duration);
            float currentValue = Mathf.Lerp(from, to, t);
            revenueAmount.text = $"${currentValue:F2}";
            yield return null;
        }

        revenueAmount.text = $"${to:F2}";
    }

    private void OnDestroy()
    {
        if (ShopManager.Instance != null)
        {
            ShopManager.Instance.onPaymentReceived -= HandleRevenueChanged;
        }
    }


    void DisplayProductPanel(Sprite productSprite, int quantity, int maxCapacity)
    {
        VisualElement root = uiDocument.rootVisualElement;

        VisualElement productImage = root.Q<VisualElement>("Product-Image");

        if (productImage != null && productSprite != null)
        {
            productImage.style.backgroundImage = new StyleBackground(productSprite);
        }
    }
}