chip-gameV3/Assets/Scripts/Common/CoinCounter.cs

104 lines
3.0 KiB
C#

using TMPro;
using UnityEngine;
using DG.Tweening;
public class CoinCounter : MonoBehaviour
{
public TextMeshProUGUI balanceLabel;
public CanvasGroup balanceSignGroup;
[SerializeField] private CanvasGroup _notEnoughSignGroup;
[SerializeField] private RectTransform _notEnoughSign;
private bool _initialized;
private Sequence _notEnoughSequence;
private Vector3 _notEnoughBaseScale;
private void OnEnable()
{
if (_initialized)
Subscribe();
}
private void OnDisable()
{
if (!_initialized)
return;
Unsubscribe();
StopNotEnoughAnimation();
}
public void Initialize()
{
_notEnoughBaseScale = _notEnoughSign.localScale;
ResetNotEnoughSign();
UpdateBalanceLabelBySettings();
_initialized = true;
Subscribe();
}
public void UpdateBalanceLabel(int newCount) => balanceLabel.text = PaymentSystem.GetPluralizedMoney(newCount);
private void UpdateBalanceLabelBySettings()
{
bool freeplay = SettingsManager.GetBool(SettingKey.FREEPLAY);
if (freeplay)
{
balanceLabel.text = "бесплатно";
balanceSignGroup.alpha = 0;
}
else
{
UpdateBalanceLabel(PaymentSystem.Balance);
balanceSignGroup.alpha = 1;
}
}
private void PlayNotEnoughAnimation()
{
const int flashesCount = 5;
const float halfFlashDuration = 0.15f;
StopNotEnoughAnimation();
_notEnoughSignGroup.alpha = 0f;
_notEnoughSign.localScale = _notEnoughBaseScale * 0.85f;
_notEnoughSequence = DOTween.Sequence();
_notEnoughSequence.Append(_notEnoughSignGroup.DOFade(1f, halfFlashDuration));
_notEnoughSequence.Join(_notEnoughSign.DOScale(_notEnoughBaseScale, halfFlashDuration).SetEase(Ease.OutBack));
_notEnoughSequence.Append(_notEnoughSignGroup.DOFade(0f, halfFlashDuration));
_notEnoughSequence.Join(_notEnoughSign.DOScale(_notEnoughBaseScale * 0.85f, halfFlashDuration).SetEase(Ease.InQuad));
_notEnoughSequence.SetLoops(flashesCount);
_notEnoughSequence.OnComplete(ResetNotEnoughSign);
_notEnoughSequence.PlayForward();
}
private void StopNotEnoughAnimation()
{
_notEnoughSequence?.Kill();
_notEnoughSequence = null;
}
private void ResetNotEnoughSign()
{
_notEnoughSignGroup.alpha = 0f;
_notEnoughSign.localScale = _notEnoughBaseScale;
_notEnoughSequence = null;
}
private void Subscribe()
{
Unsubscribe();
PaymentSystem.OnBalanceChanged += UpdateBalanceLabel;
PaymentSystem.OnNotEnoughMoney += PlayNotEnoughAnimation;
SettingsManager.OnSettingsChanged += UpdateBalanceLabelBySettings;
}
private void Unsubscribe()
{
PaymentSystem.OnBalanceChanged -= UpdateBalanceLabel;
PaymentSystem.OnNotEnoughMoney -= PlayNotEnoughAnimation;
SettingsManager.OnSettingsChanged -= UpdateBalanceLabelBySettings;
}
}