簡體   English   中英

試圖從變量中減去 1,但它減去了 3。C# Unity

[英]Trying to subtract 1 from a variable, but it's subtracting 3. C# Unity

我試圖在按下空格時將敵人的生命值減少 1,但是當按下空格時,該值會減少 3。當程序首次運行時,變量enemyHealth的值為 4:

程序第一次運行時

按下空格后,變量返回 1。如果連續按下空格,則該值保持遞減 3:

按下空格后

將從 enemyHealth 減去的代碼移動到 void start 會產生相同的結果。

從敵人的健康中減去的代碼行運行了 3 次,這導致了問題。 但是,我不知道它為什么要運行 3 次。

播放器.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    private GameObject enemy;
    private Enemy enemyScript;

    // Start is called before the first frame update
    void Start()
    {
        enemy = GameObject.Find("Battle_Dummy");
        enemyScript = enemy.GetComponent<Enemy>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            enemyScript.enemyHealth--;
        }
    }
}

敵人.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public int enemyHealth = 4;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

請檢查您是否多次附加該行為。

通常Input.GetKeyDown(KeyCode.Space)應該只觸發一次,並且只有在您再次釋放它后才會觸發。 你可以嘗試做一些像這樣的事情記住它被觸發並手動重置它(盡管根據文檔不需要這樣做):

public class Player : MonoBehaviour
{
    private GameObject enemy;
    private Enemy enemyScript;
    private bool handledSpaceBar;

    // Start is called before the first frame update
    void Start()
    {
        enemy = GameObject.Find("Battle_Dummy");
        enemyScript = enemy.GetComponent<Enemy>();
    }

    // Update is called once per frame
    void Update()
    {
        if (!handledSpaceBar && Input.GetKeyDown(KeyCode.Space))
        {
            enemyScript.enemyHealth--;
            handledSpaceBar = true;
        }
        if (handledSpaceBar && Input.GetKeyUp(KeyCode.Space))
        {
            handledSpaceBar = false;
        }
    }
}

暫無
暫無

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

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