Hi guys,
As part of a current project I’m working on I needed to implement a colour picker.
After seeing a few requests in this forum I thought it would be helpful to share the code with you guys.
public static Color ColorPicker(Rect rect, Color color)
{
//Create a blank texture.
Texture2D tex = new Texture2D(40,40);
GUILayout.BeginArea(rect,"","Box");
#region Slider block
GUILayout.BeginHorizontal();
GUILayout.BeginVertical("Box");
//Sliders for rgb variables betwen 0.0 and 1.0
GUILayout.BeginHorizontal();
GUILayout.Label("R",GUILayout.Width(10));
color.r = GUILayout.HorizontalSlider(color.r,0f,1f);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("G",GUILayout.Width(10));
color.g = GUILayout.HorizontalSlider(color.g,0f,1f);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("B",GUILayout.Width(10));
color.b = GUILayout.HorizontalSlider(color.b,0f,1f);
GUILayout.EndHorizontal();
GUILayout.EndVertical();
#endregion
//Color Preview
GUILayout.BeginVertical("Box",new GUILayoutOption[]{GUILayout.Width(44),GUILayout.Height(44)});
//Apply color to following label
GUI.color = color;
GUILayout.Label(tex);
//Revert color to white to avoid messing up any following controls.
GUI.color = Color.white;
GUILayout.EndVertical();
GUILayout.EndHorizontal();
//Give color as RGB values.
GUILayout.Label("Current Colour = " + (int)(color.r * 255) + "|" + (int)(color.g * 255) + "|" + (int)(color.b * 255));
GUILayout.EndArea();
//Finally return the modified value.
return color;
}
The ColorPicker works in exactly the same way as a TextField or Toggle item in the standard Unity GUI which is as follows.
Color someColor = Color.white;
void OnGUI() {
someColor = ColorPicker(new Rect(0,0,120,120),someColor);
}
Let me know if you have any issues with this, and I hope it helps make your own projects a little bit easier!
Elis