当输入被按下 x 次时做某事

When input is pressed x times do something

我目前正在使用 Unity 开发一款游戏,但无法完成某些事情。我想要它,以便当输入被按下 x 次(近战攻击)时,角色停止工作,直到您按下另一个按钮 x 次,即 10 次。玩家应该能够攻击,即 3 次,但是当他这样做时,角色会进入 "fake death" 状态,他无法再与玩家一起行走或近战攻击。届时玩家应该再按 10 次其他键,然后玩家将能够再次进行近战攻击。我以为我可以用一个简单的 if 和 else 语句来实现这一点,但到目前为止还没有让它工作。由于某种原因,我的 else 部分立即执行,而不是在使用近战攻击 5 次后执行。

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

public class MeleeCounter : MonoBehaviour {

    public int attackNumber = 0;

    public GameObject meleeHitbox;

    // Update is called once per frame
    void Update () {
        if (attackNumber < 5 && Input.GetButtonDown ("Fire3"))
        {
            attackNumber++; // increment the counter
            meleeHitbox.gameObject.SetActive (true);
            Debug.Log ("Attack");
        }
        if (Input.GetButtonUp ("Fire3")) {
            meleeHitbox.gameObject.SetActive (false);
        }
        else
        {
            GetComponent<PlayerController>().enabled = false;
            Debug.Log ("Too many attacks");
            // Here should come a script that if i.e. Fire4 is pressed 10 times reset attackNumer to 0; and set PlayerController to true.
        }
    }
}

看来你把条件搞混了。正如目前编写的那样,无论玩家攻击了多少次,只要 Input.GetButtonUp ("Fire3") 为 false(也就是每当 Fire3 尚未被释放时),您的代码就会执行 else 块;你写的两个 if 语句是相互独立的。

else 语句确实应该附加到 attackNumber,而不是 Input.GetButtonUp ("Fire3") 的结果。此外,一旦 attackNumber 已更新,您可能希望在攻击发生后立即禁用播放器脚本。

这里的代码稍微改了一下,应该更接近你想要完成的:

void Update () {
    // Only bother checking for Fire3 if attacks can still be made
    if (attackNumber < 5)
    {
        if (Input.GetButtonDown ("Fire3"))
        {
            attackNumber++; // increment the counter
            meleeHitbox.gameObject.SetActive (true);
            Debug.Log ("Attack");

            // Detect when too many attacks are made only if an attack was just made
            if (attackNumber == 5) {
                GetComponent<PlayerController>().enabled = false;
                Debug.Log ("Too many attacks");
            }
        }
    }
    // If attacks can't be made, then check for Fire4 presses
    else
    {
        // Here should come a script that if i.e. Fire4 is pressed 10 times reset attackNumer to 0; and set PlayerController to true.
    }

    // Allow disabling of the hitbox regardless of whether attacks can be made, so it isn't left active until after the player is enabled again
    if (Input.GetButtonUp ("Fire3")) {
        meleeHitbox.gameObject.SetActive (false);
    }
}

希望对您有所帮助!如果您有任何问题,请告诉我。