I took the following code from HexConverter - Unify Community Wiki
string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2");
This gives me the exception:
FormatException: The specified format 'X2' is invalid
I tried then to use "D"
but even this threw an error. The only thing working is "F
for formatting float numbers.
Go to declaration reveals mscorlib.dll/System/Single.ToString (string) in assembly browser - sounds good so far.
Googling for monodevelop string format hex or similar search strings did not show anything interesting regarding restrictions in MonoDevelop.
So is there anything to prepare, initialise, ... before I can get a simple hex value Conversion?
[Update] Color is a struct in Unity:
public struct Color
{
public float r;
public float g;
public float b;
// ...
Taking dtb's answer I finally got it working using:
int r = (int)(color.r * 256);
int g = (int)(color.g * 256);
int b = (int)(color.b * 256);
string hex = string.Format ("{0:X2}{1:X2}{2:X2}", r, g, b);
So I missed the fact that Color
defines its components as float
instead of int
and the integral types thing dtb has mentioned.
[Update-2] More elegant solution:
Color32 color32 = color;
string hex = color32.r.ToString ("X2") + color32.g.ToString ("X2") + color32.b.ToString ("X2");