簡體   English   中英

Unity3D C#不會轉到else語句(調用重復)

[英]Unity3D C# not going to the else statement (Invoke Repeating)

我目前正在使用用C#編寫的Unity3D制作我的第一款游戲。 我剛剛遇到了一些游戲錯誤,已經花了幾個小時來思考我的代碼可能有什么問題,但是我看不到任何錯誤。

我有一個名為healthRegen的統計信息,每秒將HP添加到角色中。 我注意到的是,即使我的播放器的HP下降到零,它也會不斷增加HP到播放器中,從而使其恢復活力。 我有一種方法可以檢查我的角色HP是否下降到零,但沒有調用它,我也不知道為什么。

   public bool fullHealth() {
        if(currentHealth >= maxHealth) {
            return true;
        } else {
            return false;
        }
    }

    public void adjustHealth() {
        if(currentHealth > maxHealth) {
            currentHealth = maxHealth;
        }

        if(currentHealth < 0) {
            currentHealth = 0;
        }
    }

那是我的方法,這是我的播放器腳本

 void Start() {
        InvokeRepeating("regenerate", 0f, 1f);
    }
    // Check if the player is still alive
    public bool isDead() {
        if (attribute.currentHealth == 0) {
            return true;        
        } else {
            return false;
        }
    }

    // Die method
    public void dead() {
        animation.Play(dieClip.name);
    }

    private void regenerate() {
        if (!attribute.fullHealth()) {
            attribute.currentHealth += attribute.healthRegen;
        } else {
            attribute.adjustHealth();
        }
    }

對於其他人來說,這可能是一個愚蠢的問題,但對不起,我不知道該怎么辦了。

我現在才找到解決方案,我忘記了CancelInvoke()方法

private void regenerate() {
    if (!attribute.fullHealth()) {
        attribute.currentHealth += attribute.healthRegen;
    } else {
        CancelInvoke("regenerate");
        attribute.adjustHealth();
    }
}

現在,它運行良好!

看來您的問題是,如果播放器的健康值為0, regenerate()會為您的播放器增加健康。

您只需要添加對isDead()的調用即可防止這種情況。

private void regenerate() {
    if (!attribute.fullHealth() && !attribute.isDead()) {
        attribute.currentHealth += attribute.healthRegen;
    } else {
        attribute.adjustHealth();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM