The following script is an example of how in Unity to countdown a number to zero while fading the text color from green to red.
I use this script and method in my Unity game Binary Blitz to countdown a bonus value as time runs out.
Here is how it looks.

Using the script
- Create a new “Bonus” C# Script in your project and past in the below script
- Add some UI Text to your scene.
- Drag your script to the Text in the inspector
- Change the public variables to fit your needs

The Script
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Bonus : MonoBehaviour { public float updateBonusEvery = 0.05f; // seconds public int MAX_BONUS = 10000; public int STEP = 30; private float timeTillBonusUpdate; public int bonusRemaining; // Use this for initialization void Start () { ResetBonus(); } // Update is called once per frame void Update () { if (GameController.instance.isPaused == false) { //Update Bonus var bonusTimer = Time.deltaTime; timeTillBonusUpdate -= bonusTimer; if (timeTillBonusUpdate <= 0) { timeTillBonusUpdate = updateBonusEvery; updateBonus(); } } } private void updateBonus() { if (bonusRemaining >= STEP) { // Reduce the remaining bnus bonusRemaining -= STEP; // Bonus Font Color float H = 0.35f / ((float)MAX_BONUS / (float)bonusRemaining); float S = 1f; // Saturation float B = 0.75f; // Brightness Color bonusColor = Color.HSVToRGB(H, S, B); //Font Colour // Change Text and Colours this.gameObject.GetComponent<Text>().color = bonusColor; this.gameObject.GetComponent<Text>().text = "Bonus: " + bonusRemaining.ToString(); } else { // We are zero float H = 0f; float S = 1f; // Saturation float B = 0.75f; // Brightness bonusRemaining = 0; Color bonusColor = Color.HSVToRGB(H, S, B); this.gameObject.GetComponent<Text>().color = bonusColor; this.gameObject.GetComponent<Text>().text = "Bonus: 0"; } } public void ResetBonus() { bonusRemaining = MAX_BONUS; timeTillBonusUpdate = updateBonusEvery; } }
Recent Comments