Ouch Unity 2020 Color32/Color Conversion changed values.

I’m attempting to update a project here which is heavily math and color based. Unity changed it’s handling of Color32 / Color Conversions since our project went live. (2018LTS) And it’s the last boulder in our conversion to 2020LTS for performance improvements.

I’m wondering how folks typically handle a breaking change in a library and what work-around to utilize old functionality instead?

In my example:

Unity used to Convert float color channel to byte via (In Color32 class):
(byte)(Mathf.Clamp01(c.r) * 255)

Now it does instead (Color32 class line 46):
(byte)(Mathf.Round((Mathf.Clamp01(c.r) * 255f))),

This leads to changed color values which we cannot have for various reasons in our project. (Even though the new implementation is slightly more balanced)

So, Do I need to make a custom Color32 Class, (of old unity code) and convert references to it?
Or is there some other less sloppy way of switching back or utilizing an older library?

Oh wow, that’s a big juicy numeric fail! Is that really the code that Unity uses??

It’s interesting that the original one was so degenerate!!! Nothing short of 1.0f will return a 255 in the byte space. That’s a pretty big discontinuity at the top of the color channel number space.

Even the current (new) implementation is completely degenerate, with shortened spaces for 0 and 255 in the floating point space. I would think the correct data-pure way would be to:

  • multiply float by 256
  • floored it always (cast to byte/int)
  • clamped it to 0-255

To see what I mean, simulate 2550 separate floating point values between 0.0 and 1.0 in Python:

#!/usr/bin/env python3

for n in range(2560):
    i = n / 2560.0

    # degenerate method from above (note how 0 and 255 are half-sized)
    a = i * 255
    a += 0.5
    a = int(a)

    # a proper even way, data purity
    b = i * 256
    if b > 255: b = 255
    b = int(b)

    print( "%6.2ff -> %3u -> %3u" % (i, a, b))

That would have been an even transition. While the official docs do not promise (AFAIK) a particular conversion process, they certainly shouldn’t change it mid-stream.

There was a guy a few days ago noting he was getting suddenly different colors.

My advice to him and you is to avoid such a lossless conversion, even if it is a stable lossless conversion (stable when Unity doesn’t change it).

Kurt - yeah, I noticed the same thing, I told my partner, If they were going to screw us with a change, at least do it well! :wink: Oh well.

1 Like