74 lines
1.9 KiB
C#

using UnityEngine;
/// <summary>
/// Îòâå÷àåò òîëüêî çà îòîáðàæåíèå è îáíîâëåíèå UI ìîíåò
/// </summary>
public class CoinUI : MonoBehaviour
{
[SerializeField] private int playerId;
[SerializeField] private Coin coin;
private int lastCoins;
private bool eventsSubscribed;
private void OnEnable()
{
ComWrapper.OnInitialize += Subscribe;
if (!eventsSubscribed && (ComWrapper.onCoinAdded != null || ComWrapper.onCoinRemoved != null))
Subscribe();
}
private void OnDisable()
{
if (eventsSubscribed)
{
if (ComWrapper.onCoinAdded != null) ComWrapper.onCoinAdded.RemoveListener(HandleCoinsChanged);
if (ComWrapper.onCoinRemoved != null) ComWrapper.onCoinRemoved.RemoveListener(HandleCoinsChanged);
eventsSubscribed = false;
}
ComWrapper.OnInitialize -= Subscribe;
}
private void Subscribe()
{
if (eventsSubscribed) return;
if (ComWrapper.onCoinAdded != null) ComWrapper.onCoinAdded.AddListener(HandleCoinsChanged);
if (ComWrapper.onCoinRemoved != null) ComWrapper.onCoinRemoved.AddListener(HandleCoinsChanged);
lastCoins = ComWrapper.GetPlayerCredits(playerId);
eventsSubscribed = true;
}
private void Start()
{
int current = ComWrapper.GetPlayerCredits(playerId);
lastCoins = current;
if (coin != null)
{
coin.ChangeCoinText($"{current}");
if (current == 0) coin.FreezeCoin();
else coin.UnfreezeCoin();
}
}
private void HandleCoinsChanged(int playerID, int newAmount)
{
if (coin == null || playerID != playerId) return;
coin.ChangeCoinText($"{newAmount}");
if (newAmount == 0) coin.FreezeCoin();
else coin.UnfreezeCoin();
if (newAmount > lastCoins)
coin.PlayAddCoinsAnimation();
lastCoins = newAmount;
}
}