CapersProject/Assets/02.Scripts/Ui/Tycoon/GoldUi.cs

76 lines
2.2 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
2024-10-08 06:13:52 +00:00
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;
2024-10-08 06:13:52 +00:00
[SerializeField]
private float _animationTime = 1f;
private Queue<int> _goldQueue = new();
2024-10-08 06:13:52 +00:00
private Coroutine _changeGoldInstance;
private bool _isAnimating;
private bool _isQuitting;
// Hashes
2024-10-08 06:13:52 +00:00
private static readonly int HighlightTriggerHash = Animator.StringToHash("highlightTrigger");
private void OnEnable()
{
2024-11-15 07:28:13 +00:00
EventManager.OnAddedGold += ChangeGold;
}
private void OnDisable()
{
if (_isQuitting) return;
2024-11-15 07:28:13 +00:00
EventManager.OnAddedGold -= ChangeGold;
}
private void OnApplicationQuit()
{
_isQuitting = true;
}
2024-11-15 07:28:13 +00:00
private void ChangeGold(int addedGold, bool isTip)
{
2024-11-15 07:28:13 +00:00
_goldQueue.Enqueue(addedGold);
2024-10-08 06:13:52 +00:00
if (!_isAnimating)
{
2024-10-08 06:13:52 +00:00
Utils.StartUniqueCoroutine(this, ref _changeGoldInstance, AnimateGoldChange());
}
}
private IEnumerator AnimateGoldChange()
{
2024-10-08 06:13:52 +00:00
_isAnimating = true;
while (_goldQueue.Count > 0)
{
var currentGold = int.Parse(_goldText.text.Replace(",", ""));
2024-11-15 07:28:13 +00:00
var targetGold = currentGold + _goldQueue.Dequeue();
var elapsedTime = 0f;
2024-10-08 06:13:52 +00:00
_goldAnimator.SetTrigger(HighlightTriggerHash);
while (elapsedTime <= _animationTime)
{
2024-10-08 06:13:52 +00:00
var newGold = (int)Mathf.Lerp(currentGold, targetGold, elapsedTime / _animationTime);
_goldText.text = newGold.ToString("N0");
2024-10-08 06:13:52 +00:00
elapsedTime += Time.deltaTime;
yield return null;
}
_goldText.text = targetGold.ToString("N0");
}
2024-10-08 06:13:52 +00:00
_isAnimating = false;
}
}
}