【问题标题】:How to scale and recolor sprite from with script Unity 2d如何使用脚本 Unity 2d 缩放和重新着色精灵
【发布时间】:2017-10-04 01:42:36
【问题描述】:

我需要缩小生命值条并更改其颜色。当前的代码不起作用,作为编码的初学者我不知道为什么。

健康条是一个白色精灵,将作为 healthBar 变量。

public void ChangeHealthBar()//not working
{
    Color red = new Color(249, 0, 0);
    scaleFactor = hurtEnemy.damageToGive / CurrentHealth;
    healthBar.transform.localScale = new Vector3(scaleFactor, scaleFactor, 1);
    healthBar.GetComponent<SpriteRenderer>().color = red;
}

【问题讨论】:

  • 你在哪里调用ChangeHealthBar()函数?

标签: c# unity3d 2d


【解决方案1】:

除了尝试缩小图像之外,您还可以将其设为filled 类型,这样您可以通过更改the fillAmount 仅显示图像的一部分,如下所示:

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.

public class Damage : MonoBehaviour
{
public Image healthBar;
public float scaleFactor;
public float currentHealth;
private Color red;

private void Start()
{
    healthBar.type = Image.Type.Filled;
    red = new Color(249, 0, 0);
}

public void ChangeHealthBar()
{
    scaleFactor = hurtEnemy.damageToGive / currentHealth;
    healthBar.fillAmount = scaleFactor;
    healthBar.color = red;
}
}

【讨论】:

    【解决方案2】:

    您可以使用它应该可以工作的代码(我现在没有时间在 Unity 中对其进行完全测试)
    您需要在更新当前健康后调用它

            float sizeMultiplicator = 1; //to manage the initial size of your bar
            public void ChangeHealthBar(int currentHealth, int maxHealth)
            {
                Color red = new Color(249, 0, 0);
                float percent = (float)currentHealth / maxHealth;
                healthBar.transform.localScale = new Vector3(percent * sizeMultiplicator, 1, 1);
                healthBar.GetComponent<SpriteRenderer>().color = red;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      相关资源
      最近更新 更多