CapersProject/Assets/02.Scripts/Ui/Tycoon/GoldUi.cs
2024-10-08 15:13:52 +09:00

76 lines
2.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using BlueWater.Utility;
using Sirenix.OdinInspector;
using TMPro;
using UnityEngine;
namespace BlueWater.Uis
{
public class GoldUi : MonoBehaviour
{
[SerializeField, Required]
private Animator _goldAnimator;
[SerializeField, Required]
private TMP_Text _goldText;
[SerializeField]
private float _animationTime = 1f;
private Queue<int> _goldQueue = new();
private Coroutine _changeGoldInstance;
private bool _isAnimating;
private bool _isQuitting;
// Hashes
private static readonly int HighlightTriggerHash = Animator.StringToHash("highlightTrigger");
private void OnEnable()
{
EventManager.OnChangeGold += ChangeGold;
}
private void OnDisable()
{
if (_isQuitting) return;
EventManager.OnChangeGold -= ChangeGold;
}
private void OnApplicationQuit()
{
_isQuitting = true;
}
private void ChangeGold(int newGoldAmount)
{
_goldQueue.Enqueue(newGoldAmount);
if (!_isAnimating)
{
Utils.StartUniqueCoroutine(this, ref _changeGoldInstance, AnimateGoldChange());
}
}
private IEnumerator AnimateGoldChange()
{
_isAnimating = true;
while (_goldQueue.Count > 0)
{
var targetGold = _goldQueue.Dequeue();
var currentGold = int.Parse(_goldText.text.Replace(",", ""));
var elapsedTime = 0f;
_goldAnimator.SetTrigger(HighlightTriggerHash);
while (elapsedTime <= _animationTime)
{
var newGold = (int)Mathf.Lerp(currentGold, targetGold, elapsedTime / _animationTime);
_goldText.text = newGold.ToString("N0");
elapsedTime += Time.deltaTime;
yield return null;
}
_goldText.text = targetGold.ToString("N0");
}
_isAnimating = false;
}
}
}