Unity : I can't change the opacity of an image or change its color in RGB

Viewed 120

In my project, I want to change the color of a square at runtime which is simply a game object with an Image component. In my script I proceed like this:

private Image imageRenderer;


imageRenderer = ImageCompleteSquat.GetComponent<Image>();
imageRenderer.color = Color.red;

In this case, it works and the image turns red as expected. But as soon as I change this line by putting my own RGB color like this:

imageRenderer.color = new Color(227, 66, 52);

The image is not displayed anymore: it disappears. Does anyone know how to change the color of an Image component?

2 Answers

you might want to set the alpha value first

imageRenderer = ImageCompleteSquat.GetComponent<Image>();
var tempColor = Color.red;
tempColor.a = 1f; // change this value (floating point between 0 and 1)
imageRenderer.color = tempColor;

From the docs of Color, each color component is a floating point value with a range from 0 to 1. Hence just divide the arguments passed into Color() by 255

imageRenderer.color = new Color(227/255f, 66/255f, 52/255f);
Related