How to parse a hex-color string in Unity C#

0 votes
asked May 20, 2015 in Programming by ismix Senior (1,150 points)

How can I parse a hex-color string in Unity?

Input: #000000

Output: Color.black

Color color = Color.Parse("#000000");

Thanks in advance!

 

 

1 Answer

+1 vote
answered May 20, 2015 by Bugstacker Senior (4,800 points)
selected May 20, 2015 by ismix
 
Best answer

Try something like this:     

using System.Globalization;
   public static Color Parse(string hexstring)
   {
            if (hexstring.StartsWith("#"))
            {
                hexstring = hexstring.Substring(1);
            }

            if (hexstring.StartsWith("0x"))
            {
                hexstring = hexstring.Substring(2);
            }

            if (hexstring.Length != 6) 
            {
                throw new Exception(string.Format("{0} is not a valid color string.", hexstring));
            }

            byte r = byte.Parse(hexstring.Substring(0, 2), NumberStyles.HexNumber);
            byte g = byte.Parse(hexstring.Substring(2, 2), NumberStyles.HexNumber);
            byte b = byte.Parse(hexstring.Substring(4, 2), NumberStyles.HexNumber);

            return new Color32(r, g, b, 1);
 }
Welcome to Bugstacker Q&A, where you can ask questions concerning Game Development, Programming and Design and receive answers from other members of the community.

Help for

...