How can I use Hex color?

if I type

image.color = Color.red;

it only makes the image red , and I think image.color = Color.___ only has 11 colors

How can I use Hex Color?
so I can choose the color that I want

100151-untitled.png

1 Like

I can't submit an answer because it is already closed but for anyone using this to answer their own question, you can also set a public color object and use the hex value in the unity editor. No advantage just another way to do it.

–

Ok! I'll try to implement it to the best of my ability, thank you so much for your help!

–

I seem to run into an error with the debug.log bit in update(), "Argument 1: cannot convert from string[] to string" I've tried googling and whatnot but i cant seem to figure out how to fix it sorry...

–

5 Answers

5

I’m pretty new to Unity but I know that the Color constructor takes 3 parameters for r(red), g(green) and b(blue). If you understand better HEX colors than rgb ones, you should use an online converter to convert a HEX color you want to a rgb color. Then you can use :

float r ;  // red component
float g ;  // green component
float b ;  // blue component
image.color = new Color(r,g,b) ;

For example, #ffffff is rgb(255,255,255).

Note:

more explain please I don't get it I write your code and it didn't do anything

–

Have you tried the ColorUtility class ?

ColorUtility.TryParseHtmlString( "#FF0000" , out Color myColor );'

Seems like a more suitable solution

Lets dispel few possible misunderstandings in this thread:

Unity - Scripting API: Color

Color struct constructor accepts RGBA float values in 0.0-1.0 range.

Color red = new Color( 1.0f , 0.0f , 0.0f , 1.0f  );

Unity - Scripting API: Color32

Color32 struct constructor accepts RGBA int values in 0-255 range.

Color32 red = new Color32( 255 , 0 , 0 , 255 );
Color32 also_red = new Color32( 0xFF , 0x00 , 0x00 , 0xFF );

Both Color and Color32 (32bit) can be used to define valid color values.

You can use the new Color(r,g,b,a) constructor, although it only takes RGBA float values, not Hex.

Not true, try this: Color32 greyColour = new Color32(0xBE, 0xBF, 0xBE, 0xFF); NB, Color32 is important, not Color

–
using System.Globalization;
using UnityEngine;

public class Colors
{
    public static Color FromHex(string hex)
    {
        if (hex.Length<6)
        {
            throw new System.FormatException("Needs a string with a length of at least 6");
        }

        var r = hex.Substring(0, 2);
        var g = hex.Substring(2, 2);
        var b = hex.Substring(4, 2);
        string alpha;
        if (hex.Length >= 8)
            alpha = hex.Substring(6, 2);
        else
            alpha = "FF";

        return new Color((int.Parse(r, NumberStyles.HexNumber) / 255f),
                        (int.Parse(g, NumberStyles.HexNumber) / 255f),
                        (int.Parse(b, NumberStyles.HexNumber) / 255f),
                        (int.Parse(alpha, NumberStyles.HexNumber) / 255f));
    }
}