CapersProject/Assets/02.Scripts/Ui/Tycoon/GoldUi.cs
Nam Tae Gun 57b21c004f 0.3.4.0
2024-11-15 16:28:13 +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.OnAddedGold += ChangeGold;
}
private void OnDisable()
{
if (_isQuitting) return;
EventManager.OnAddedGold -= ChangeGold;
}
private void OnApplicationQuit()
{
_isQuitting = true;
}
private void ChangeGold(int addedGold, bool isTip)
{
_goldQueue.Enqueue(addedGold);
if (!_isAnimating)
{
Utils.StartUniqueCoroutine(this, ref _changeGoldInstance, AnimateGoldChange());
}
}
private IEnumerator AnimateGoldChange()
{
_isAnimating = true;
while (_goldQueue.Count > 0)
{
var currentGold = int.Parse(_goldText.text.Replace(",", ""));
var targetGold = currentGold + _goldQueue.Dequeue();
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;
}
}
}