Friend me on FacebookFollow me on Twitter! @Caruanas Follow me on LinkedIn!

Beware Unity's project Colour Space setting

Last week I was experimenting with some custom shaders and noticed that when I output a hardcoded colour (from C# code or directly in the shader itself) it returns a different colour than expected. For example return float4(0.5f, 0.5f, 0.5f, 1.0f); gave me #BCBCBC instead of #808080 as expected. However, I also noticed that if I define a property (which becomes visible to the inspector) and return its value (untouched/unedited), it results in the correct colour.

Naturally this meant that the issue was somehow related to the fact that Unity was in some way processing the property value such that it is evaluated correctly...which also did not make sense to me since I did not think it needed any alternative evaluation.

After a couple of days of hair-pulling, a post to the Unity support forum pointed me in the right direction. It turns out that somehow my project was set to use linear space lighting instead of the (usual, expected) gamma space. So Unity was properly converting the inspector-selected colour to linear space whereas my hardcoded values were not! (0.5, 0.5, 0.5 is naturally valid in both linear and gamma, but translates to #BCBCBC in the former and #808080 in the latter).

So if you want to work in linear space, you need to convert your values. A quick, although quite inaccurate method (depending on the target platform) of doing this is to raise the RGB values to a power of 2.2

Otherwise do as I did and if you don't specifically need linear lighting (which in 3D environments can offer a more realistic effect), make sure your project is set to gamma space rendering via "Edit -> Project Settings -> Player -> Other Settings"

Note that linear lighting is not supported on all platforms.

More details can be found at

Unity colour space setting

Subscribe to my newsletter