Unity新UI图像更改颜色不起作用

has*_*ash 4 c# unity-game-engine unity3d-2dtools

我尝试使用统一的新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;

         }
Run Code Online (Sandbox Code Playgroud)

我得到这个错误.

  error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Graphic.color'. Consider storing the value in a temporary variable
Run Code Online (Sandbox Code Playgroud)

Sen*_*cob 11

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

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

因此,如果您要应用红色,请确保使用它

gameObject.GetComponent<Image>().color = new Color(1f, 0f, 0f);
Run Code Online (Sandbox Code Playgroud)

代替

gameObject.GetComponent<Image>().color = new Color(255, 0, 0); // this won't change the image color
Run Code Online (Sandbox Code Playgroud)


Chr*_*and 8

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

Image healthImage = GameObject.Find("health").GetComponent<Image>();
Color newColor = healthImage.color;
newColor.a = 1;
healthImage.color = newColor;
Run Code Online (Sandbox Code Playgroud)