Changing the "Albedo" color in the material?

How can I do this in csharp?

3 Likes

Material.color, or Material.SetColor with the appropriate property name (“_Color” in this case).

–Eric

3 Likes

When I do that, it remove my dust material and make the material a flat color.

Setting the color doesn’t remove the texture. You probably just used a color that has too much saturation or brightness.

–Eric

could you please tell me How can I use a color with not much saturation or brightness

Hey Helix,
it’s been a long time this thread has not been answered. But anyway, I recently had the same problem as you had around 3 years ago. I see that there was no final answer here. So I will show you and probably all other people who have the same problem, how to come to a solution.

Main problem:
The values in the Shader component in the inspector for the AlbedoColor are ranging from 0-255 for RGBA.
R = Red, G = Green, B = Blue, A = Alpha

Now, when you try to set the values via C# in your own script, suddenly the RGBA values only range from 0-1. Which means from 0% to 100%, where 100% is corresponding to the AlbedoColor Value 255 in the Inspector.

Example:
Imagine you have a dark red color as the AlbedoColor. In the inspector you have the following values:

R = 200
G = 0
B = 0
A = 255

In case you transfer the inspector values one by one into the C# code, you’ll tell the shader, that red should have 20000%, resulting into a very very bright red color.

For solving this issue, you have to calculate the percentage value for R = 200.
As soon as you have calculated the percentage amount from 200 of the max value 255, which is around 78%, you can set the new color with the following line of code:

gameObject.GetComponent<Renderer>().material.color = new Color(0.78f, 0, 0, 1);

I hope I could help you!

10 Likes

Thank you DonPuno, it helped me get my randomly coloured game object working.
I needed the RGB-values to always add up to a total of 1:

        float redX = Random.Range(0, 256);
        float greenX = Random.Range(0, 256);
        float blueX = Random.Range(0, 256);
        float colourSum = redX + greenX + blueX;
        redX = redX / colourSum;
        greenX = greenX / colourSum;
        blueX = blueX / colourSum;

        gameObject.GetComponent<Renderer>().material.color = new Color(redX, greenX, blueX, 1);
3 Likes

Variable “Color” is float value from 0.0f to 1.0f - white is (1f,1f,1f,1f)
Variable “Color32” is byte from 0 to 255 - white = (255, 255, 255, 255)

Color32 helps if your color picking in Photoshop and want those values :slight_smile:

1 Like

Thanks for the reference! :slight_smile: