4

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
Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
hash
  • 5,336
  • 7
  • 36
  • 59

5 Answers5

14

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;
Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
11

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
Sen Jacob
  • 3,384
  • 3
  • 35
  • 61
0

Or,

Image healthImage = GameObject.Find("health").GetComponent<Image>();
healthImage.color = Color.red;
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
Durk
  • 1
0
 if (health_value == 3) 
{
   GameObject playerHealthImage = GameObject.Find("health").GetComponent<Image>();
   Color healthColor = playerHealthImage.color;

   healthColor.a=1;
   
  //Or          red,Green,Blue,Alpha    

  healthColor = new Color(1,1,1,1);
  playerHealthImage.color = healthColor;
}

You cannot modify Colors RGBA values independently because it's a structure.how ever you can directly assign Color based on above.

Omdevsinh Gohil
  • 145
  • 1
  • 4
  • Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Ran Marciano Apr 05 '21 at 11:26
0
GameObject imageGameObject;

// 1.0 - 0.0
float r; 
float g; 
float b; 
float a; 
imageGameObject.GetComponent<Image>().color = new Color(r, g, b, a);

// 255-0
int r32; 
int g32; 
int b32; 
int a32; 
imageGameObject.GetComponent<Image>().color = new Color32(r32, g32, b32, a32);