How to get the Color Code in RGB Hex from RGBA? (Unity 3D 5.0f1)

I actually got stuck at this point where I’m doing the following and to get color code in RGB Hex from Unity Color

  1. loading an image from camera into a RawImage.texture as Texture2D which displays just fine.(there is no material set to RawImage but it has solid white color in the start)

  2. then i am using my touched position(using Input.GetButtonDown(“Fire1”) and Input.mousePosition ) on the image as coordinates into my_texture.GetPixel(x,y);

  3. But the color code convertion which i applied gave me always #010101 which translates to black on online color converters.

               Texture2D my_texture = RawImageEnlarge.texture as Texture2D;
    
    		int x = (int)my_position.x;
    		int y = (int)my_position.y;
    
    		Color my_color = my_texture.GetPixel(x, y);
    		//TODO must remove after testing ------
    
    		//blend alpha : converting argb to rgb 
    		Color blend = Color.white; 
    		int alpha = (int)my_color.a;
    		int r = (int)((alpha/255)*my_color.r + (1 - alpha/255)*blend.r);
    		int g = (int)((alpha/255)*my_color.g + (1 - alpha/255)*blend.g);
    		int b = (int)((alpha/255)*my_color.b + (1 - alpha/255)*blend.b);
    
    
    		string hexCC = "#"+r.ToString("X2") + g.ToString("X2") + b.ToString("X2");
    
    //OR //string hexCC = UnityEngine.ColorUtility.ToHtmlStringRGB(my_color); //unity does not recognize ColorUtility class :/
    

4 Answers

4

You guys are all trying way too hard. Just use ColorUtility.ToHtmlStringRGB( myColor ) and get on with it.

To be exact: ColorUtility.ToHtmlStringRGBA( myColor ) RGBA ... not just RGB :)

Thanks a lot!

Looked everywhere and all I've been seeing is confusing methods, formulas and conversions. You're a life saver, thank you!

Absolutely the best answer there is. Still up to date, and the cleanest way of doing this.

well, unfortunately, what you're asking for is not trivial. It looks as though they are using some kind of beam effect, and is slow dying. If you make the gameobject create the particle effect while its attached to the tip of your ray cast, it should work... this is all theory though.

So, here’s a basic example that may work. I have not tested all possible values of color channels, but I tested each channel, not a number, positive and negative infinity, alpha etc, to make sure the output stays within #000000 to #FFFFFF and doesn’t throw exceptions. You may wish different behaviour for negative, positive infinity or not a number cases perhaps, but this is up to what makes sense to you. In most cases, you won’t be feeding those values into any channel anyway.

using UnityEngine;

public static class ColorTypeConverter
{
    public static string ToRGBHex(Color c)
    {
        return string.Format("#{0:X2}{1:X2}{2:X2}", ToByte(c.r), ToByte(c.g), ToByte(c.b));
    }

    private static byte ToByte(float f)
    {
        f = Mathf.Clamp01(f);
        return (byte)(f * 255);
    }
}

And the tests for reference.

using NUnit.Framework;
using UnityEngine;

[TestFixture]
[Category("Type Conversion")]
internal class ColorTypeConverterTests
{
    [Test]
    public void ConvertsCommonColors()
    {
        Assert.AreEqual("#000000", ColorTypeConverter.ToRGBHex(Color.black));
        Assert.AreEqual("#FFFFFF", ColorTypeConverter.ToRGBHex(Color.white));
    }

    [Test]
    public void IgnoresAlphaChannel()
    {
        Assert.AreEqual("#FFFFFF", ColorTypeConverter.ToRGBHex(new Color(1, 1, 1, 0)));
        Assert.AreEqual("#FFFFFF", ColorTypeConverter.ToRGBHex(new Color(1, 1, 1, 1)));
    }

    [Test]
    public void ConvertsChannelsInRGBOrder()
    {
        Assert.AreEqual("#FF0000", ColorTypeConverter.ToRGBHex(Color.red));
        Assert.AreEqual("#00FF00", ColorTypeConverter.ToRGBHex(Color.green));
        Assert.AreEqual("#0000FF", ColorTypeConverter.ToRGBHex(Color.blue));
    }

    [Test]
    public void ConvertsYellow()
    {
        UnityYellowIsKnown();
        Assert.AreEqual("#FFEB04", ColorTypeConverter.ToRGBHex(Color.yellow));
    }

    [Test]
    public void UnityYellowIsKnown()
    {
        // ConvertsYellow use yellow color. If Unity changes the definition of 
        // yellow, those tests will fail. To spare developer confusion about 
        // failing tests, assert that the channels are known. Because the channels
        // are so arbitrary, it's also nice to see the floats in plain text.
        Assert.AreEqual(1, Color.yellow.r, "Color.yellow.r changed");
        Assert.AreEqual(0.921568632f, Color.yellow.g, "Color.yellow.g changed");
        Assert.AreEqual(0.0156862754f, Color.yellow.b, "Color.yellow.b changed");
    }

    [Test]
    public void ClampsChannelsBetweenZeroAndOne()
    {
        Assert.AreEqual("#FFFFFF", ColorTypeConverter.ToRGBHex(PosInf()));
        Assert.AreEqual("#FFFFFF", ColorTypeConverter.ToRGBHex(Fill(1.5f)));
        Assert.AreEqual("#FFFFFF", ColorTypeConverter.ToRGBHex(Fill(1)));
        Assert.AreEqual("#000000", ColorTypeConverter.ToRGBHex(Fill(0)));
        Assert.AreEqual("#000000", ColorTypeConverter.ToRGBHex(Fill(-0.5f)));
        Assert.AreEqual("#000000", ColorTypeConverter.ToRGBHex(NegInf()));
    }

    [Test]
    public void NotANumberConvertsToBlack()
    {
        Assert.AreEqual("#000000", ColorTypeConverter.ToRGBHex(NaN()));
    }

    private static Color NaN()
    {
        return Fill(float.NaN);
    }

    private static Color NegInf()
    {
        return Fill(float.NegativeInfinity);
    }

    private static Color PosInf()
    {
        return Fill(float.PositiveInfinity);
    }

    private static Color Fill(float c)
    {
        return new Color(c, c, c, c);
    }
}

great answer with excellent unit tests!

I was able to get this working but I think its not giving me correct color code.
i cant patch it up. Help highly apreciated!

        Texture2D t2d = RawImageEnlarge.texture as Texture2D;
		int x = (int)ClickedPosition.x;
		int y = (int)ClickedPosition.y;
		//(RawImageEnlarge.texture as Texture2D).format = TextureFormat.RGB24;

		Color my_color = (t2d).GetPixel(x, y);
		Color32 myyyy_color = my_color;
		Debug.Log ("MYY COLOR: "+my_color);
		Debug.Log ("MYYYYYY COLOR: "+myyyy_color);
		//TODO must remove after testing ------

		//blend alpha : converting argb to rgb 
		Color blend = Color.white; 
		int alpha = (int)myyyy_color.a;
		int r = (int)((alpha/255)*myyyy_color.r + (1 - alpha/255)*blend.r);
		int g = (int)((alpha/255)*myyyy_color.g + (1 - alpha/255)*blend.g);
		int b = (int)((alpha/255)*myyyy_color.b + (1 - alpha/255)*blend.b);

		//                        OR                       // now working atm
		//ColorTranslator.ToHtml (Color.FromArgb (Color.Tomato.ToArgb ()));

		string hexCC = "#"+r.ToString("X2") + g.ToString("X2") + b.ToString("X2");
		
			//string hexCC = ColorUtility.ToHtmlStringRGB(my_color);
		
		ColorCodeCC.text = hexCC;

Hey,

To convert Unity Color (RGB) to HEX code, it has to be an Int32.

// C#
Color color = new Color(69, 12,  65);
int r = (int)color.r, g = (int)color.g, b = (int)color.b;
string _color = r.ToString("X2") + g.ToString("X2") + b.ToString("X2");

Best regards, Arthur

Tagging the main reply as the correct answer. I was erroneously using a rigidbody as a bullet and applying force to it, when instead I should have been simply lerping from the muzzle point to the impact point. Gives a very nice bullet shooting effect. Point to note is that I used a long plane as the bullet, with the texture fading out on both ends to make it look nice and sassy instead of using a trail renderer, which doesn't do as good a job as this one. Thanks a bunch for your help.