C# 试图从变量中减去1,但它';s减去3。统一

C# 试图从变量中减去1,但它';s减去3。统一,c#,visual-studio,unity3d,C#,Visual Studio,Unity3d,我试图在按下空格键时将敌人的生命值降低1,但当按下空格键时,该值会降低3。程序首次运行时,变量enemyHealth的值为4: 按下空格后,变量返回为1。如果按顺序按下空格键,则该值将持续减少3: 将从enemyHealth中减去的代码移动到void start会产生相同的结果 从敌人的生命值中减去的代码行运行了3次,这导致了问题。一、 但是,我不知道为什么它会运行3次 Player.cs: using System.Collections; using System.Collections

我试图在按下空格键时将敌人的生命值降低1,但当按下空格键时,该值会降低3。程序首次运行时,变量enemyHealth的值为4:

按下空格后,变量返回为1。如果按顺序按下空格键,则该值将持续减少3:

将从enemyHealth中减去的代码移动到void start会产生相同的结果

从敌人的生命值中减去的代码行运行了3次,这导致了问题。一、 但是,我不知道为什么它会运行3次

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

请检查您是否多次附加该行为

通常
Input.GetKeyDown(KeyCode.Space)
应该只触发一次,并且只有在您再次释放它之后才会触发。您可以尝试这样做,以记住它已触发并手动重置它(尽管根据文档,不需要此):

公共类玩家:单行为
{
私人游戏对象敌人;
私人敌人的敌人;
私人布尔把手空格键;
//在第一帧更新之前调用Start
void Start()
{
敌人=游戏对象。查找(“战斗假人”);
enemyScript=敌方.GetComponent();
}
//每帧调用一次更新
无效更新()
{
if(!handledSpaceBar&&Input.GetKeyDown(KeyCode.Space))
{
enemyScript.enemyHealth--;
handledSpaceBar=true;
}
if(handledSpaceBar&&Input.GetKeyUp(KeyCode.Space))
{
handledSpaceBar=false;
}
}
}


GetKeyDown
仅在按下键后的第一次
更新时为
true
。同样适用于
GetKeyUp
,但在释放钥匙时。您的
HandleSpaceBar
是多余的,因为它内置于
GetKeyDown/GetKeyUp
功能中。我建议添加
Debug.Log(gameObject.name+“伤害敌人”)在你伤害(或以其他方式修改)敌人生命之前。这将告诉您脚本附加到哪个对象以及它运行的频率。(您也可以记录
Time.Time
以查看它是否在同一个更新中)@Immersive,经过一些调试后,我注意到它运行了3次,这是什么原因造成的?
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()
    {

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