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");
From MSDN:
The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". This format is supported only for integral types.
Single
is a floating-point type, not an integral type.
Use an Int32
:
int value = 10;
string result = value.ToString("X2");
// result == "0A"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With