Skip to content

Instantly share code, notes, and snippets.

@llamacademy
Last active March 14, 2024 08:47
Show Gist options
  • Save llamacademy/e651518eebc09650cc7b66492aefe58e to your computer and use it in GitHub Desktop.
Save llamacademy/e651518eebc09650cc7b66492aefe58e to your computer and use it in GitHub Desktop.
Scripts from the Animate Text video https://www.youtube.com/watch?v=SbDiFLfFcCs. If you get value from LlamAcademy, consider becoming a Patreon supporter at https://www.patreon.com/llamacademy
using System.Collections;
using TMPro;
using UnityEngine;
[RequireComponent(typeof(TextMeshProUGUI))]
public class NumberCounter : MonoBehaviour
{
public TextMeshProUGUI Text;
public int CountFPS = 30;
public float Duration = 1f;
public string NumberFormat = "N0";
private int _value;
public int Value
{
get
{
return _value;
}
set
{
UpdateText(value);
_value = value;
}
}
private Coroutine CountingCoroutine;
private void Awake()
{
Text = GetComponent<TextMeshProUGUI>();
}
private void UpdateText(int newValue)
{
if (CountingCoroutine != null)
{
StopCoroutine(CountingCoroutine);
}
CountingCoroutine = StartCoroutine(CountText(newValue));
}
private IEnumerator CountText(int newValue)
{
WaitForSeconds Wait = new WaitForSeconds(1f / CountFPS);
int previousValue = _value;
int stepAmount;
if (newValue - previousValue < 0)
{
stepAmount = Mathf.FloorToInt((newValue - previousValue) / (CountFPS * Duration)); // newValue = -20, previousValue = 0. CountFPS = 30, and Duration = 1; (-20- 0) / (30*1) // -0.66667 (ceiltoint)-> 0
}
else
{
stepAmount = Mathf.CeilToInt((newValue - previousValue) / (CountFPS * Duration)); // newValue = 20, previousValue = 0. CountFPS = 30, and Duration = 1; (20- 0) / (30*1) // 0.66667 (floortoint)-> 0
}
if (previousValue < newValue)
{
while(previousValue < newValue)
{
previousValue += stepAmount;
if (previousValue > newValue)
{
previousValue = newValue;
}
Text.SetText(previousValue.ToString(NumberFormat));
yield return Wait;
}
}
else
{
while (previousValue > newValue)
{
previousValue += stepAmount; // (-20 - 0) / (30 * 1) = -0.66667 -> -1 0 + -1 = -1
if (previousValue < newValue)
{
previousValue = newValue;
}
Text.SetText(previousValue.ToString(NumberFormat));
yield return Wait;
}
}
}
}
using TMPro;
using UnityEngine;
public class NumberCounterUpdater : MonoBehaviour
{
public NumberCounter NumberCounter;
public TMP_InputField InputField;
public void SetValue()
{
int value;
if (int.TryParse(InputField.text, out value))
{
NumberCounter.Value = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment