Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hex to Color(RGBA) with TryParseHtmlString

Tags:

c#

colors

unity3d

How can I change the button color in Unity, using HEX values?
I tried this, but it doesn't work, perhaps I made a mistake here:

btn.image.color = ColorUtility.TryParseHtmlString(DADADAFF, out color); 
like image 549
Rumata Avatar asked Oct 26 '17 19:10

Rumata


1 Answers

You are assigning bool to Color(btn.image.color).

ColorUtility.TryParseHtmlString returns bool not Color if successful. You get the output color in the second parameter then take that and assign it to the Button. Only use the output color if ColorUtility.TryParseHtmlString returns true.

Below is what that code should look like:

string htmlValue = "#FF0000";
Button btn = GetComponent<Button>();

Color newCol;

if (ColorUtility.TryParseHtmlString(htmlValue, out newCol))
{
    btn.image.color = newCol;
}

To convert the Color back to hex:

Color newCol = Color.red;
string htmlValue = ColorUtility.ToHtmlStringRGBA(newCol);

So there is no way to just assign Hex color without checking that it can be converted to RGB first?

There is. Remove the if statement.

ColorUtility.TryParseHtmlString(htmlValue, out newCol);
btn.image.color = newCol;

Don't do this as your Color result may be wrong. You should handle this with the if statement like I did in the first code.

like image 159
Programmer Avatar answered Nov 17 '22 05:11

Programmer