Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Reliably converting material color between Color and Color32

Discussion in 'General Graphics' started by CarlY, Dec 24, 2015.

  1. CarlY

    CarlY

    Joined:
    Nov 5, 2013
    Posts:
    29
    I'm doing image analysis on my rendered images. Here's my problem. After assigning a color to my material, the color's RGB value in the framebuffer and the one returned by unity via Color32 is different and it's been driving me insane. It's most probably caused by float to int conversion but I couldn't find a way to make them align.

    Code (csharp):
    1. //pseudo code
    2. Color NewColor = new Color(0.123f,0.43f,0.37f,1f);
    3. gameObject.GetComponent<Renderer>().material.color = NewColor;
    4. Color32 NewColorRGB = NewColor;
    5. NewColorRGB.r //returns 31 when framebuffer is 32
    6. NewColorRGB.g //returns 109 when framebuffer is 110
    7. NewColorRGB.b //returns 94 which is correct
     
  2. CarlY

    CarlY

    Joined:
    Nov 5, 2013
    Posts:
    29
    OK, I think I found the solution. Initial tests seem OK. Do this for each color channel.

    Code (csharp):
    1. NewColorRGB_R = (int)Math.Round(InColor.r * 255.0f, MidpointRounding.AwayFromZero);
     
  3. CarlY

    CarlY

    Joined:
    Nov 5, 2013
    Posts:
    29
    Unfortunately, this is not working for all cases. Any suggestions.
     
  4. imaginaryhuman

    imaginaryhuman

    Joined:
    Mar 21, 2010
    Posts:
    5,834
    It won't work for all situations perfectly because you're using floats. How do you know that 255.0 can be exactly represented and not as 244.999939 or something?

    Also beware of any effects from linear/gamma color.