4using System.Globalization;
9 [RequireComponent(typeof(InputField))]
16 private InputField hexInputField;
18 private const string hexRegex =
"^#?(?:[0-9a-fA-F]{3,4}){1,2}$";
22 hexInputField = GetComponent<InputField>();
25 hexInputField.onEndEdit.AddListener(UpdateColor);
29 private void OnDestroy()
31 hexInputField.onValueChanged.RemoveListener(UpdateColor);
35 private void UpdateHex(
Color newColor)
37 hexInputField.text = ColorToHex(newColor);
40 private void UpdateColor(
string newHex)
46 Debug.Log(
"hex value is in the wrong format, valid formats are: #RGB, #RGBA, #RRGGBB and #RRGGBBAA (# is optional)");
49 private string ColorToHex(Color32 color)
52 return string.Format(
"#{0:X2}{1:X2}{2:X2}{3:X2}", color.r, color.g, color.b, color.a);
54 return string.Format(
"#{0:X2}{1:X2}{2:X2}", color.r, color.g, color.b);
57 public static bool HexToColor(
string hex, out Color32 color)
60 if (System.Text.RegularExpressions.Regex.IsMatch(hex, hexRegex))
62 int startIndex = hex.StartsWith(
"#") ? 1 : 0;
64 if (hex.Length == startIndex + 8)
66 color =
new Color32(
byte.Parse(hex.Substring(startIndex, 2), NumberStyles.AllowHexSpecifier),
67 byte.Parse(hex.Substring(startIndex + 2, 2), NumberStyles.AllowHexSpecifier),
68 byte.Parse(hex.Substring(startIndex + 4, 2), NumberStyles.AllowHexSpecifier),
69 byte.Parse(hex.Substring(startIndex + 6, 2), NumberStyles.AllowHexSpecifier));
71 else if (hex.Length == startIndex + 6)
73 color =
new Color32(
byte.Parse(hex.Substring(startIndex, 2), NumberStyles.AllowHexSpecifier),
74 byte.Parse(hex.Substring(startIndex + 2, 2), NumberStyles.AllowHexSpecifier),
75 byte.Parse(hex.Substring(startIndex + 4, 2), NumberStyles.AllowHexSpecifier),
78 else if (hex.Length == startIndex + 4)
80 color =
new Color32(
byte.Parse(
"" + hex[startIndex] + hex[startIndex], NumberStyles.AllowHexSpecifier),
81 byte.Parse(
"" + hex[startIndex + 1] + hex[startIndex + 1], NumberStyles.AllowHexSpecifier),
82 byte.Parse(
"" + hex[startIndex + 2] + hex[startIndex + 2], NumberStyles.AllowHexSpecifier),
83 byte.Parse(
"" + hex[startIndex + 3] + hex[startIndex + 3], NumberStyles.AllowHexSpecifier));
87 color =
new Color32(
byte.Parse(
"" + hex[startIndex] + hex[startIndex], NumberStyles.AllowHexSpecifier),
88 byte.Parse(
"" + hex[startIndex + 1] + hex[startIndex + 1], NumberStyles.AllowHexSpecifier),
89 byte.Parse(
"" + hex[startIndex + 2] + hex[startIndex + 2], NumberStyles.AllowHexSpecifier),
96 color =
new Color32();
ColorChangedEvent onValueChanged
ColorPickerControl ColorPicker
static bool HexToColor(string hex, out Color32 color)