Search code examples
c#unity-game-enginecolors

How to convert hex to Color(RGBA) with TryParseHtmlString


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); 

Solution

  • 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.