首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Unity - Zelda life system在更新hp容器时崩溃

Unity - Zelda life system在更新hp容器时崩溃
EN

Stack Overflow用户
提问于 2017-06-27 04:13:10
回答 1查看 63关注 0票数 0

我用5个健康容器构建了一个Zelda健康系统。每个容器有4块。

当更新这个健康条时,我得到一个超出范围的异常。

我的代码:

代码语言:javascript
复制
[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时,它会在

代码语言:javascript
复制
healthContainers[healthContainerIndex].fillAmount = 0;

因为.。

代码语言:javascript
复制
int healthContainerIndex = currentHealth / healthPerHealthContainer;

结果:

代码语言:javascript
复制
healthContainerIndex = 5;

包含5个容器的数组的索引范围为0到4。

而是简单地写

代码语言:javascript
复制
healthContainers[healthContainerIndex -1].fillAmount = 0;

是错误的,因为我需要得到正确的心脏。有没有人明白我在这里犯的错误?我看不到它..

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-27 04:51:40

绝对同意Jon Skeet把它写在一张纸上,这对解决这样的索引问题真的很有帮助。

话虽如此,您可能需要重新考虑您的解决方案是否会按您希望的方式工作。你的解决方案只适用于假设玩家的生命值一次只上升或下降一个生命值。如果玩家受到足够的伤害或者他们的健康完全恢复,你的解决方案可能会跳过一步,心脏可能不会正确更新。如果你只是迭代所有的容器并更新它们,它将更容易实现,也更健壮。

代码语言:javascript
复制
public void UpdateHealthBar() // gui updater
{
    for (int healthContainerIndex = 0; healthContainerIndex < healthContainers.Length; healthContainerIndex++)
    {
        healthContainers[healthContainerIndex].fillAmount = Mathf.Clamp01((float)currentHealth / healthPerHealthContainer - healthContainerIndex);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44767936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档