4

我正在尝试使用统一的新 UI 图像系统为我的玩家实现健康。但它不起作用。任何人都可以帮助我。谢谢。

    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;

         }

我收到这个错误。

  error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Graphic.color'. Consider storing the value in a temporary variable
4

5 回答 5

11

因为 Color 是 Image 的结构体(我认为这是正确的术语?如果我错了请纠正我),你不能直接编辑它的颜色,你必须创建一个新的 Color var,改变它的 vars,然后将其分配给图像。

Image healthImage = GameObject.Find("health").GetComponent<Image>();
Color newColor = healthImage.color;
newColor.a = 1;
healthImage.color = newColor;
于 2015-03-05T04:12:25.853 回答
6

我有同样的问题,但由于不同的原因。因此,如果接受的答案不是他们的问题,这可能对其他人有所帮助。

请注意,Unity 期望脚本中的颜色值在 0-1 范围内

因此,如果您使用红色,请确保您使用它就像

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

代替

gameObject.GetComponent<Image>().color = new Color(255, 0, 0); // this won't change the image color
于 2020-06-25T10:51:09.240 回答
0

或者,

Image healthImage = GameObject.Find("health").GetComponent<Image>();
healthImage.color = Color.red;
于 2015-09-14T10:22:35.757 回答
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;
}

您不能独立修改颜色 RGBA 值,因为它是一个结构。但是您可以Color根据上面的内容直接分配。

于 2021-04-05T09:02:14.557 回答
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);
于 2021-07-06T04:31:30.647 回答