Home > database >  Does Unity have a way to convert a Color into it's string name equivalent from knownColor?
Does Unity have a way to convert a Color into it's string name equivalent from knownColor?

Time:06-16

In Unity, there are some colors predefined. Like Color.red. But there are only 8 of them, which doesn't even include orange! I already know that I can make any kind of color, but I need to get the string name of each color I.E. Color.red => "red" or "Red" and I'm wondering if theres a way to turn it into a C# KnownColor, and pull the name from that?

The use-case is that I have a radial menu color selector, and I'd like to display the name of each color below the color preview.

I am currently using this function:

private static String GetColorName(Color color, bool caps = false) {
    var colorProperty = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static).FirstOrDefault(p=>(Color)(p.GetValue(p, null)) == color);
    return (colorProperty != null) ? caps ? string.Concat(colorProperty.Name[0].ToString().ToUpper(), colorProperty.Name.Substring(1)) : colorProperty.Name : color.ToString();
}

Which does work, but I want to expand it to use the KnownColors instead of the Unity Colors.

I would love to avoid needing to manage a dictionary or the like of colors.

CodePudding user response:

No unfortunately there is not. however, to solve what you are trying to achieve you can create a dictionary with the color's string name and the actual RGBA value of the color.

 IDicionary colorDictionary;

 void Start()
 {
    colorDictionary = new Dictionary<string, Color>();
    
    colorDictionary.Add("Black", Color.Black);
    colorDictionary.Add("White", Color.White);
    colorDictionary.Add("Orange", new Color(1f, 0.64f, 0f, 1f));
    colorDictionary.Add("Hot Pink", new Color(1f, 0.4f, 0.7f, 1f)); 
 }

Then from the dictionary you can display the color and the string.

CodePudding user response:

You can build your own dictionary via reflection, and store it in a static variable;

static Dictionary<Color, string> byName =
    typeof(Color)
    .GetProperties(BindingFlags.Public | BindingFlags.Static)
    .Where(p => p.PropertyType == typeof(Color))
    .ToDictionary(p => (Color)p.GetValue(null), p => p.Name);

But only those exact hues will be in there.

If you wanted to name any colour, you could either take the above list, or maybe the XKCD color survey results and use some function to find the closest named colour. Perhaps via Pythagoras in either the RGB or HSV color space.

  • Related