Rodlaiz

TextMeshPro Colorize characters

Jul 16th, 2020
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. using UnityEngine;
  2. using TMPro;
  3. using System.Collections;
  4.  
  5. [RequireComponent(typeof(TextMeshProUGUI))]
  6. public class TextmeshProColorizer : MonoBehaviour
  7. {
  8. public TextMeshProUGUI txt;
  9. public bool animateColors;
  10. public float animationSpeed;
  11.  
  12. [Space(10)]
  13.  
  14. [Header("Colors palette")]
  15. public Color[] colors;
  16.  
  17. private string[] _hexStrings;
  18.  
  19. private int _hexIndex;
  20. private int _txtIndex;
  21. private string _originalTxt;
  22.  
  23. private string _coloredText = "";
  24.  
  25. private void Start()
  26. {
  27. _originalTxt = txt.text;
  28.  
  29. //Initialize the _hexStrings array with the number of colors in the palette
  30. _hexStrings = new string[colors.Length];
  31.  
  32. //Populate the _hexStrings array with the hex code for each color in the palette
  33. for (int i = 0; i < colors.Length; i++)
  34. {
  35. _hexStrings[i] = ColorUtility.ToHtmlStringRGB(colors[i]);
  36. }
  37.  
  38. if (!animateColors)
  39. {
  40. //Use only ApplyColors() if we don't want to have the colors animated.
  41. ApplyColors();
  42. }
  43. else
  44. {
  45. //Use AnimateColors() if we want to have the colors animated.
  46. StartCoroutine(AnimateColors());
  47. }
  48. }
  49.  
  50. private void ApplyColors()
  51. {
  52.  
  53. //We iterate over our text string and create a colored text string stored in _coloredText
  54. for (int i = 0; i < txt.text.Length; i++)
  55. {
  56. _coloredText = _coloredText + "<#" + _hexStrings[_hexIndex] + ">" + txt.text[i].ToString() + "</color>";
  57.  
  58. //We skip the hex index increment if the character in the txt is a space
  59. if (txt.text[i] != ' ')
  60. {
  61. _hexIndex++;
  62. if (_hexIndex > _hexStrings.Length - 1)
  63. _hexIndex = 0;
  64. }
  65. }
  66.  
  67. //We assign the colored version of our text to the text field;
  68. txt.text = _coloredText;
  69. }
  70.  
  71. private IEnumerator AnimateColors()
  72. {
  73. ApplyColors();
  74.  
  75. yield return new WaitForSeconds(animationSpeed);
  76.  
  77. //We offset the hex color index of 1 so the colors will shuffle
  78. _hexIndex++;
  79. if (_hexIndex > _hexStrings.Length - 1)
  80. _hexIndex = 0;
  81.  
  82. _coloredText = "";
  83. txt.text = _originalTxt;
  84.  
  85. //We start the animation again
  86. StartCoroutine(AnimateColors());
  87. }
  88. }
Add Comment
Please, Sign In to add comment