Support different color spaces in Unity

You probably know, that Unity supports two different color spaces: Linear and Gamma. Usually, linear color space is the preferred option. Unless you publish on a platform where only the gamma color space is supported. Unity provides some information on the impacts of the color space.

Why do the colors look weird?

Whenever this happens, chances are high that you are working in the wrong color space. For example, if you follow a shader tutorial: Your output looks similar to the tutorial, but not exactly.

If you are working on a small project, you can simply change the color space in the project settings. Then you’ll immediately see if the wrong color space was the root of your problem.

In a large project, changing the color space may take very long. Therefore it’s better to directly test the gamma correction in a shader.

To apply gamma correction manually, you have to add the following code.

rgb = pow(rgb, 2.2f);

And in the other direction, you add the following code to remove the gamma correction:

color.rgb = pow(rgb, 0.454545f);

Support both color spaces

Which color space should you target in a reusable package?

Either you select one of them and make it clear in the documentation. Or you are kind to your customers (or your future self) and support both color spaces.

Luckily, Unity provides a built-in shader define UNITY_COLORSPACE_GAMMA.

In case your shader works for the gamma color space, you can use the following function at the end of your color computations. If the project uses the gamma color space, nothing needs to be done. If the project uses the linear color space, the gamma correction is applied manually.

half3 ApplyGammaCorrection(half3 rgb)
{
#if !UNITY_COLORSPACE_GAMMA
    return pow(rgb, 2.2f);
#endif
}
Prev
Spatial Computing

Spatial Computing

Human interaction with the real space

Next
Video See-Through AR

Video See-Through AR

Create augmented reality with VR headsets