我正在尝试在我的游戏中实现一个最大生命值为1000的健康栏。1000的生命值除以20个方格,每个方格代表50点生命值。所发生的是,健康条控制器脚本通过每个正方形和"x“的数量,它们都满了。然后,"x+1“方格将被部分填充,这取决于先前的健康方格中剩下多少健康值,每个健康方格各有50个生命值。剩下的健康方块就不会显示出来,看起来是看不见的。我面临的问题是,部分显示的健康单元不是部分显示,而是完全或根本不显示。我知道,我实现的使卫生单元正常工作的代码是有效的,因为当我对部分填充的健康单元的填充量使用Debug.log时,填充量将显示在控制台中,将其设置为浮动。我正在使用映像UI Gameobject中的图像组件来更改健康单元的fillAmount。
下面是我的帮助代码:
保健栏本身的代码:
public void Update_Health(int health)
{
//HEALTH UNITS ARE IMAGE OBJECTS THAT ARE CREATED BY PREFABS AND STORED IN HEALTH UNITS ARRAY SHOWN BELOW:
int number_full = health / 50;
for (int y = 0; y < number_full; y++)
{
health_units[y].GetComponent<Health_Unit_Controller>().Display_full();
}
if (number_full != 20)//USED FOR THE PARTIALLY DISPLAYED HEALTH UNIT
{
int number_remaining = 20 - number_full;
int remainder_health = health - (number_full * 50);
health_units[number_full].GetComponent<Health_Unit_Controller>().Display_partially(remainder_health);
for (int a = (20 - number_remaining); a < 20; a++)
{
health_units[a].GetComponent<Health_Unit_Controller>().Display_partially(0);
}
}
}每个卫生单位的代码:
public class Health_Unit_Controller : MonoBehaviour, I_Unit
{
private Image image_componenet;//getting the image componenet from the image UI object.
void Start()
{
image_componenet = GetComponent<Image>();
}
public void Display_full()
{
image_componenet.fillAmount = 1;
}
public void Display_partially(int health_remaining)
{
if (health_remaining != 0)
{
image_componenet.fillAmount = health_remaining / 50.0f;
Debug.Log("health_remaining: " + image_componenet.fillAmount);
}
else
{
image_componenet.fillAmount = 0;
}
}
}下面是一些帮助您的图表:

在这张图中,红色方块代表健康单位。如上文所示,有2个医疗单位已经隐形。这两个医疗单位中有一个应该是隐形的。尽管控制台显示的填充量表明第二个健康单元的填充量应该为0.8f,但另一个健康单元也已完全不可见。相反,所发生的是,第二个健康单位似乎根本没有出现。
发布于 2021-08-05 21:59:33
你试过简化代码吗?您正在存储许多变量,最好通过一个函数来运行所有这些变量。
public void DisplayHealth(int health){
int hp = health;
for (int i = 0; i < 20 (or health_units length); i++) {
health_units[i].GetComponent<Health_Unit_Controller>().Display_partially(health);
health -= 50;
}另外,我会把你的部分功能从
public void Display_partially(int health_remaining)
{
if (health_remaining != 0)
{
image_componenet.fillAmount = health_remaining / 50.0f;
Debug.Log("health_remaining: " + image_componenet.fillAmount);
}转到
public void Display_partially(int health_remaining)
{
if (health_remaining > 50)
{
image_componenet.fillAmount = 1
}
else if (health_remaining <= 0)
{
image_componenet.fillAmount = 0f;
}
else
{
image_componenet.fillAmount = health_remaining / 50f;
}https://stackoverflow.com/questions/68667560
复制相似问题