我用5个健康容器构建了一个Zelda健康系统。每个容器有4块。
当更新这个健康条时,我得到一个超出范围的异常。
我的代码:
[SerializeField]
Image[] healthContainers; // 5 containers as images
int currentHealth;
int maxHealth;
int healthPerHealthContainer = 4; // 1 healthcontainer = 4 health pieces
private void Start()
{
maxHealth = healthContainers.Length * healthPerHealthContainer; // set max hp
currentHealth = maxHealth; // init current hp
UpdateHealthBar(); // first gui update
}
public void ChangeHealth(int amount) // get damage or heal
{
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth); // add or subtract health
UpdateHealthBar(); // update gui
}
public void UpdateHealthBar() // gui updater
{
int healthContainerIndex = currentHealth / healthPerHealthContainer; // get the current heart to change
int healthContainerFillAmount = currentHealth % healthPerHealthContainer; // the fillamount of the heart
if (currentHealth % healthPerHealthContainer == 0)
{
if (currentHealth == healthContainers.Length)
{
healthContainers[healthContainerIndex - 1].fillAmount = 1;
return;
}
if (healthContainerIndex > 0)
{
healthContainers[healthContainerIndex].fillAmount = 0;
healthContainers[healthContainerIndex - 1].fillAmount = 1;
}
else
{
healthContainers[healthContainerIndex].fillAmount = 0;
return;
}
}
healthContainers[healthContainerIndex].fillAmount = healthContainerFillAmount / (float)healthPerHealthContainer;
}因此,当使用5个健康容器,每个健康使用4个健康容器时,我从20马力开始。更新gui时,它会在
healthContainers[healthContainerIndex].fillAmount = 0;因为.。
int healthContainerIndex = currentHealth / healthPerHealthContainer;结果:
healthContainerIndex = 5;包含5个容器的数组的索引范围为0到4。
而是简单地写
healthContainers[healthContainerIndex -1].fillAmount = 0;是错误的,因为我需要得到正确的心脏。有没有人明白我在这里犯的错误?我看不到它..
发布于 2017-06-27 04:51:40
绝对同意Jon Skeet把它写在一张纸上,这对解决这样的索引问题真的很有帮助。
话虽如此,您可能需要重新考虑您的解决方案是否会按您希望的方式工作。你的解决方案只适用于假设玩家的生命值一次只上升或下降一个生命值。如果玩家受到足够的伤害或者他们的健康完全恢复,你的解决方案可能会跳过一步,心脏可能不会正确更新。如果你只是迭代所有的容器并更新它们,它将更容易实现,也更健壮。
public void UpdateHealthBar() // gui updater
{
for (int healthContainerIndex = 0; healthContainerIndex < healthContainers.Length; healthContainerIndex++)
{
healthContainers[healthContainerIndex].fillAmount = Mathf.Clamp01((float)currentHealth / healthPerHealthContainer - healthContainerIndex);
}
}https://stackoverflow.com/questions/44767936
复制相似问题