We have an EmissionColor that is HDR enabled, and we’d like to adjust its intensity value directly through C# (I’d prefer not to touch our post-processing shaders). I feel this should be an easy solution, but I haven’t found an answer for this specific question (this question is the closest one, but I’m not looking to swap colors- just adjust a color’s intensity value). Here’s sample code:
Color colorToDisplay = targetMat.GetColor("_EmissionColor");
/*I want to do something like this:
if(colorToDisplay.Intensity > 0.5)
{
colorToDisplay.Intensity = 1;
}*/
targetMat.SetColor("_EmissionColor", colorToDisplay);
I could use a few Color.Lerps, since I’m getting the intensity value to transition that way, but it’s clunky for what I’d like to do. I could also follow bgolus’s response in this thread, but I’m curious to know if there’s a simpler way. Thank you for your time!
I search a lot before found the solution, I don’t found it on documentation, but finally, it was simple. I found the operation done by colorPicker by analyzing values changes in RGB mode when we change intensity parameter. The operation is just 2^intensity.
There is the solution:
float factor = Mathf.pow(2,intensity);
Color color = new Color(red*factor,green*factor,bleue*factor);
Color struct consist of 4 floats for each channel. To create a higher intensity color, simply set its values to something higher than 1. Intensity exists in the color picker editor, but it’s probably just an editor value that multiplies all channels by it (that’s my guess).
So, define the ‘intensity’ first. Let’s say it’s the average of rgb channels
var intensity = (color.r + color.g + color.b) / 3f;
then, if you want to set an intensity to a specific value, find out how much you need to increase the intensity of each channel. If you want to ‘normalize’ the intensity (set it to 1) you’d do something like
var factor = 1f / intensity;
where factor is the value you will multiply the color’s rgb by:
color = new Color(color.r * factor, color.g*factor, color.b * factor, color.a);
Now, if your original color wasn’t gray, one or more channels will be higher than 1 (which is the top LDR value)
I am reviving this to add a few details that weren’t obvious to me. Assuming you have created a shader material called MyMaterial with HDR color property named _Color. You can use the code from the UnityEditor.ColorMutator class to modify the HDR color (exposureAdjustedColor) or intensity (exposureValue) of a material at runtime like this…
// Use existing color, just modify the intensity
ColorMutator cm = new(MyMaterial.GetColor("_Color"));
cm.exposureValue = 10;
MyMaterial.SetColor("_Color", cm.exposureAdjustedColor);
// Modify both color and intensity
ColorMutator cm = new(Color.green);
cm.exposureValue = 10;
MyMaterial.SetColor("_Color", cm.exposureAdjustedColor);
Of course you would need to the ColorMutator code included in your project to be able to run outside the editor.