Changing Color Of Image not working with non-default colors.
Hey everyone, im currently stuck at the point where i can change image's color with default colors but not with the colors declared in inspector tab (under the script). It changes the color of image in inspector tab, but not in the game. For example;
sq1.GetComponent<Image>().color = Color.blue;
code above works perfectly when i call this inside the update function. But when i get colors as input like:
public Color defaultColor;
public Color frameColor;
sq1.GetComponent<Image>().color = defaultColor;
This doesn't change the color of image, instead it literally deletes the image. I declared colors in RGB code ( like sq1.GetComponent().color = new Color(41,135,45,255) ) but this doesn't work either. I can just use predefined colors.
Thank you so much for your interest.
Answer by JPhilipp · Feb 15, 2020 at 11:33 AM
Instead of
sq1.GetComponent().color = new Color(41,135,45,255);
try
Renderer renderer = gameObject.GetComponent<Renderer>();
renderer.material.color = new Color32(41, 135, 45, 255);
Note how I'm using Color32 -- because you provide the values as bytes or integers, not 0-1 floats -- and I'm also grabbing the renderer material to assign the color. For repeat speedy access of renderer, you may want to declare a class scope variable to cache its reference.
Your answer
Follow this Question
Related Questions
None, not even the most simple scripts work!!!! example... 0 Answers
Gravity not working with character control script 1 Answer
Destroying prefabs breaking scripting for other prefabs 0 Answers
Changing Imported Mesh Color through code 0 Answers
How to make bullet prefab take color of the character? 1 Answer