c# - Unity UI image.fill 数量未部分显示图像
问题描述
我正在尝试在我的游戏中实现一个最大生命值 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 个生命值单位消失了。这 2 个健康单位中的 1 个应该是不可见的。但是即使控制台显示的填充量表明第二个生命单元的填充量应该是 0.8f,另一个生命单元也完全不可见。相反,第二个健康单位似乎根本没有出现。
解决方案
您是否尝试过简化代码?您正在存储许多变量,最好通过一个函数运行所有这些。
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;
}
推荐阅读
- php - WordPress中带有wp_nav_menu()函数的移动导航菜单问题
- c - 基本 C 代码中报告的语法错误 - 出了什么问题?
- reactjs - 如何在测试中更改反应状态
- ios - 以编程方式在 UITableViewCell 子视图中使用约束
- php - Heroku:只有“/”在我的 php 应用程序上工作
- python - 如果 ttk 小部件名称或 StringVar 不是全局的,则默认文本不会显示
- python - 使用 sqlite3 和 python 按索引将表拆分为 2 个新表
- reactjs - 为什么调试器要求我再次弹出?
- django - 从模板将参数传递给视图函数而不在 URL 中公开它
- oracle - 如何为 PL SQL 中的现有表创建唯一 ID?