【问题标题】:Why does the Unity sprite color not change with my update function? [duplicate]为什么 Unity 精灵颜色不会随着我的更新功能而改变? [复制]
【发布时间】:2018-05-01 03:53:47
【问题描述】:

在我正在创建的当前游戏中,我试图让生命值条颜色动态变化,以对应敌人的当前生命值。当生命值达到最大值时,条形图将为绿色 (0, 255, 0),当生命值低时,条形图将接近红色 (255, 0, 0)。我将函数编码为根据敌人当前的健康状况从绿色变为红色。当敌人处于半血状态时,颜色应该是 (125, 125, 0),但是每当我开始游戏时,敌人就会以全血(绿色)开始,一旦血量不再处于最大值,条形图也是相同的黄色直到敌人死去。我的代码的哪一部分导致 Unity 不能同时出现颜色?

public void Start()
{
    health = maxHealth;
    healthBar.fillAmount = 1;
}

public void Update()
{
    canvas.transform.LookAt(tranformTarget);
    healthBar.fillAmount = health / maxHealth;

    greenColor = (int)(255 * healthBar.fillAmount);
    redColor = (int)(-255 * healthBar.fillAmount + 255);
    Color healthBarColor = new Color(redColor, greenColor, 0, 255);
    healthBar.color = healthBarColor;
    Debug.Log(greenColor);
    Debug.Log(redColor);
}

【问题讨论】:

  • health和fillAmount有哪些类型?从绿色到红色的 RGB 渐变也不好看。最好在 HSL 中进行。
  • fillAmount 是 0 到 1。health 是一个从 0 到 100 的整数。
  • 这是关于c#,而不是unityscript

标签: c# unity3d


【解决方案1】:

您的代码不会像您希望的那样工作,因为 Unity 的颜色适用于法线。 https://docs.unity3d.com/ScriptReference/Color-ctor.html

所以你需要一个介于 0-1 之间的浮点数。

试试这个。

canvas.transform.LookAt(tranformTarget);
healthBar.fillAmount = health / maxHealth;

var green = healthBar.fillAmount;
var red = -1 * healthBar.fillAmount + 1;
Color healthBarColor = new Color(red, green, 0f, 1f);
healthBar.color = healthBarColor;

请注意,如果您只是希望 alpha 为 1,也可以省略 alpha 参数。

【讨论】:

  • 谢谢!我现在知道了。
猜你喜欢
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多