Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using TMPro;
- using System.Collections;
- [RequireComponent(typeof(TextMeshProUGUI))]
- public class TextmeshProColorizer : MonoBehaviour
- {
- public TextMeshProUGUI txt;
- public bool animateColors;
- public float animationSpeed;
- [Space(10)]
- [Header("Colors palette")]
- public Color[] colors;
- private string[] _hexStrings;
- private int _hexIndex;
- private int _txtIndex;
- private string _originalTxt;
- private string _coloredText = "";
- private void Start()
- {
- _originalTxt = txt.text;
- //Initialize the _hexStrings array with the number of colors in the palette
- _hexStrings = new string[colors.Length];
- //Populate the _hexStrings array with the hex code for each color in the palette
- for (int i = 0; i < colors.Length; i++)
- {
- _hexStrings[i] = ColorUtility.ToHtmlStringRGB(colors[i]);
- }
- if (!animateColors)
- {
- //Use only ApplyColors() if we don't want to have the colors animated.
- ApplyColors();
- }
- else
- {
- //Use AnimateColors() if we want to have the colors animated.
- StartCoroutine(AnimateColors());
- }
- }
- private void ApplyColors()
- {
- //We iterate over our text string and create a colored text string stored in _coloredText
- for (int i = 0; i < txt.text.Length; i++)
- {
- _coloredText = _coloredText + "<#" + _hexStrings[_hexIndex] + ">" + txt.text[i].ToString() + "</color>";
- //We skip the hex index increment if the character in the txt is a space
- if (txt.text[i] != ' ')
- {
- _hexIndex++;
- if (_hexIndex > _hexStrings.Length - 1)
- _hexIndex = 0;
- }
- }
- //We assign the colored version of our text to the text field;
- txt.text = _coloredText;
- }
- private IEnumerator AnimateColors()
- {
- ApplyColors();
- yield return new WaitForSeconds(animationSpeed);
- //We offset the hex color index of 1 so the colors will shuffle
- _hexIndex++;
- if (_hexIndex > _hexStrings.Length - 1)
- _hexIndex = 0;
- _coloredText = "";
- txt.text = _originalTxt;
- //We start the animation again
- StartCoroutine(AnimateColors());
- }
- }
Add Comment
Please, Sign In to add comment