This articele will show you how to use an ectension method to convert HEX strings to Unity colors.

Using HEX colors in unity.

Unity supports hex colors with TryParseHtmlString and by creating a Color32 object and feed it hex values for r, g, b and a.

ToColor extension method

Many years ago I wrote a ToColor extension method to use in XAML apps. It converts strings like FFFF00, #FF0000 and #FF345699 to XAML colors and brushes. I modified the code to support unity colors and here is how you can use it in your project:

using System;
using UnityEngine;

public static class StringEx
{
// Example: "#ff000099".ToColor() red with alpha ~50%
    // Example: "ffffffff".ToColor() white with alpha 100%
    // Example: "00ff00".ToColor() green with alpha 100%
    // Example: "0000ff00".ToColor() blue with alpha 0%
    public static Color ToColor(this string color)
{
if (color.StartsWith("#", StringComparison.InvariantCulture))
{
    color = color.Substring(1); // strip #
        }

if (color.Length == 6)
{
    color += "FF"; // add alpha if missing
        }

var hex = Convert.ToUInt32(color, 16);
var r = ((hex & 0xff000000) >> 0x18) / 255f;
var g = ((hex & 0xff0000) >> 0x10) / 255f;
var b = ((hex & 0xff00) >> 8) / 255f;
var a = ((hex & 0xff)) / 255f;

return new Color(r, g, b, a);
}
}

How to use the ToColor extension method?

ToColor accepts:

Here are some examples:

var red = "#ff0000".ToColor();
var green = "00FF00".ToColor();
var blue50percent = "#0000ff99".ToColor();

If you feed the function with any other format, it will crash spectacularly.

Written by Loek van den Ouweland on 2018-05-01.
Questions regarding this artice? You can send them to the address below.