[英]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.