In the Unity game engine, ColorUtility is a built-in static scripting class that provides convenient functions to convert colors to and from HTML/Hexadecimal string formats.
It simplifies color management when you need to handle user text inputs, integrate with web APIs, or format rich text strings for UI elements. Core Methods ColorUtility contains exactly three primary static methods:
TryParseHtmlString: Converts a string representation of a color into a Unity Color object. It outputs a boolean indicating whether the parsing succeeded.
ToHtmlStringRGB: Converts a Unity Color object into a 6-digit hex string formatted as RRGGBB.
ToHtmlStringRGBA: Converts a Unity Color object into an 8-digit hex string formatted as RRGGBBAA (including alpha transparency). 1. Converting Hex Strings to Unity Colors
The TryParseHtmlString method is highly flexible. It supports standard # prefixes, raw hex values, and literal strings. using Use code with caution. UnityEngine Use code with caution.
; public class ColorExample : MonoBehaviour { void Start() { // 1. Parsing a hex string with a hashtag if (ColorUtility.TryParseHtmlString(“#FF5733”, out Color customColor)) { Debug.Log(“Successfully parsed color!”); } // 2. Parsing literal names (supports red, blue, lime, aqua, etc.) if (ColorUtility.TryParseHtmlString(“lime”, out Color limeColor)) { // limeColor is now ready to use } } } Use code with caution. Supported Formats: #RGB (e.g., #F00 becomes solid red) #RRGGBB (e.g., #FF0000) #RGBA or #RRGGBBAA (for transparency)
Literal strings: Names like red, cyan, blue, darkblue, purple, yellow, lime, fuchsia, white, silver, grey, black, orange, brown, maroon, green, olive, navy, teal, and aqua. 2. Converting Unity Colors to Hex Strings
This is incredibly useful when you want to use Unity UI Rich Text tags to colorize text strings dynamically dynamically. using Use code with caution. UnityEngine Use code with caution.
; using type = UnityEngine.UI; public class RichTextExample : MonoBehaviour { public Color myTextColor = Color.green; void Start() { // Convert color to string “RRGGBB” string hexColor = ColorUtility.ToHtmlStringRGB(myTextColor); // Output: Use code with caution. Summary Comparison Input Type Output Format TryParseHtmlString string bool (outputs Color) User hex input fields, API endpoints ToHtmlStringRGB Color string (“RRGGBB”) Basic UI formatting, database storage ToHtmlStringRGBA Color string (“RRGGBBAA”) UI text requiring transparency tracking
If you are building an in-game editor, custom color picker, or working heavily with system text files, ColorUtility eliminates the need to manually compute bit-shifted integer or normalized float conversions.
Scripting API: ColorUtility.TryParseHtmlString – Unity – Manual
Leave a Reply