- Home /
Hex colors in unity
This is bothering me for quite some time: How can you use hex color values in your script, without the need to convert it first. Is there a simple script or asset everyone is using? I can't be the only one that finds this representation for a color value strange (at least coming from a web background).
Answer by Jessespike · Jul 29, 2015 at 04:43 PM
An extension could be written to fit your needs. I haven't found it strange to use only numeric RGB values, though I would prefer to have the option available, even if I don't use them frequently. What we can do, is use the TryParseHexString function:
Color myColor = new Color();
Color.TryParseHexString("#F00", out myColor);
@Jessespike Since I updated to 5.2.0 the TryParseHexString vanished.
The new way is:
ColorUtility.TryParseHtmlString (hexString, out color);
Answer by FSpark · Sep 14, 2016 at 12:36 PM
@simpleplaystudio In case anyone else stumbles across this - you can also use hex notation directly e.g. Color myColor = new Color32( 0x2B, 0xB1, 0xD2, 0xFF ); // RGBA
The following simple test wount work with your code:
Color myColor = new Color(0xc6,0xe7, 0x45, 0xFF);
string colorHex = ColorUtility.ToHtmlStringRGB(myColor);
Assert.AreEqual("c6e745", colorHex);
colorHex will be FFFFFF. This is due to ColorUtility.ToHtmlStringRGB expects r,g,b in 0..1 range. But you provide them in 0..255
Simply because he has used new Color32
, not new Color
Answer by Fragmental · May 21, 2018 at 08:56 PM
You can also create a public color variable and then assign the hex to that variable through the color picker in the inspector. You can do the same with color blocks, if your using UI objects. It's not ideal, but for the sake of completeness, I thought I should mention it.
Your answer
Follow this Question
Related Questions
Making a Game Accessible for the Blind and Visually Impaired 4 Answers
Best way to mix color values? 4 Answers
Set Gameobject a certain color based off of other game objects 1 Answer
Random Color 1 Answer
RGB Colors as Float Values Converter 0 Answers