简体   繁体   English

试图从变量中减去 1,但它减去了 3。C# Unity

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

I'm trying to reduce an enemy's health by 1 when space is pressed, but when space is pressed, the value is decreased by 3. When the program first runs the variable enemyHealth has a value of 4:我试图在按下空格时将敌人的生命值减少 1,但是当按下空格时,该值会减少 3。当程序首次运行时,变量enemyHealth的值为 4:

程序第一次运行时

After space is pressed the variable returns as 1. If space is sequentially pressed the value keeps decreasing by 3:按下空格后,变量返回 1。如果连续按下空格,则该值保持递减 3:

按下空格后

Moving the code that subtracts from enemyHealth to void start yields the same result.将从 enemyHealth 减去的代码移动到 void start 会产生相同的结果。

The line of code that subtracts from the enemy's health is running 3 times, which is causing the problem.从敌人的健康中减去的代码行运行了 3 次,这导致了问题。 I, however, have no idea why it's running 3 times.但是,我不知道它为什么要运行 3 次。

Player.cs:播放器.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--;
        }
    }
}

Enemy.cs:敌人.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()
    {

    }
}

Please check if you attached the behaviour multiple times.请检查您是否多次附加该行为。

Usually Input.GetKeyDown(KeyCode.Space) should fire only once and only fire after you released it again.通常Input.GetKeyDown(KeyCode.Space)应该只触发一次,并且只有在您再次释放它后才会触发。 You can try to do somtething like this to remember it fired and reset it manually (although this should not be needed according to the documentation):你可以尝试做一些像这样的事情记住它被触发并手动重置它(尽管根据文档不需要这样做):

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;
        }
    }
}

See

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM