Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity New UI Image changing Color not working

im trying implement health to my player using unity new UI Image system.but its not working.can anyone help me.Thank you.

    using UnityEngine.UI;

 if (health_value == 3) {
             GameObject.Find("health").GetComponent<Image>().color.a = 1;
             GameObject.Find("health1").GetComponent<Image>().color.a = 1;
             GameObject.Find("health2").GetComponent<Image>().color.a = 1;

         }

im getting this error.

  error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Graphic.color'. Consider storing the value in a temporary variable
like image 754
hash Avatar asked Dec 06 '22 22:12

hash


2 Answers

Because the Color is a struct of Image (I think that's the correct terminology? please correct me if I'm wrong), you can't edit its color directly, you have to create a new Color var, change its vars, and then assign it to Image.

Image healthImage = GameObject.Find("health").GetComponent<Image>();
Color newColor = healthImage.color;
newColor.a = 1;
healthImage.color = newColor;
like image 75
Chris McFarland Avatar answered Dec 13 '22 04:12

Chris McFarland


I had the same issue, but because of different reason. So this might help for someone else if the accepted answer was not their issue.

Please note that Unity expects color values in 0-1 range in script.

So if you are applying red color, make sure you are using it like

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

instead of

gameObject.GetComponent<Image>().color = new Color(255, 0, 0); // this won't change the image color
like image 37
Sen Jacob Avatar answered Dec 13 '22 04:12

Sen Jacob