简体   繁体   中英

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:

程序第一次运行时

After space is pressed the variable returns as 1. If space is sequentially pressed the value keeps decreasing by 3:

按下空格后

Moving the code that subtracts from enemyHealth to void start yields the same result.

The line of code that subtracts from the enemy's health is running 3 times, which is causing the problem. I, however, have no idea why it's running 3 times.

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

Enemy.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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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