using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // Controls the text displaying the current Mana amount. When the player's amount of // Mana changes, this visually interpolates smoothly between old and new value. // Additionally, does a color flash effect. public class CurrentManaText : MonoBehaviour, IManaChangeCallback { [SerializeField] float manaUpdateTime = 0.5f; [SerializeField] float colorFlashTime = 0.2f; [SerializeField] Color manaGainColor = Color.green; [SerializeField] Color manaLossColor = Color.red; [SerializeField] Color defaultColor = Color.white; Text manaText; int previousMana = 0; int currentlyDisplayedValue = 0; float animationProgress = float.PositiveInfinity; float colorFlashProgress = float.PositiveInfinity; void Awake() { manaText = GetComponent<Text>(); StatsManager.instance.manaChangeCallbacks.Add(this); previousMana = currentlyDisplayedValue = StatsManager.instance.GetMana(); manaText.text = currentlyDisplayedValue.ToString(); manaText.color = defaultColor; } void Update() { if (animationProgress < manaUpdateTime) { // Animate between displayed and actual Mana value animationProgress += Time.deltaTime; currentlyDisplayedValue = (int)Mathf.Lerp(previousMana, StatsManager.instance.GetMana(), animationProgress / manaUpdateTime); manaText.text = currentlyDisplayedValue.ToString(); } var flashColor = currentlyDisplayedValue > previousMana ? manaGainColor : manaLossColor; if (colorFlashProgress < colorFlashTime) { // Fade flashed color back to default color colorFlashProgress += Time.deltaTime; manaText.color = Color.Lerp(flashColor, defaultColor, colorFlashProgress / colorFlashTime); } } public void OnManaChanged(int oldValue, int newValue) { animationProgress = 0f; colorFlashProgress = 0f; previousMana = currentlyDisplayedValue; } }