【问题标题】:When input is pressed x times do something当输入被按下 x 次时做某事
【发布时间】:2017-02-01 19:46:29
【问题描述】:

我目前正在 Unity 中开发一款游戏,但无法完成某些工作。我想要这样当输入被按下 x 次(近战攻击)时,角色停止工作,直到你按下另一个按钮 x 次,即 10 次。玩家应该能够攻击,即 3 次,但是当他这样做时,角色会进入“假死”状态,无法再与玩家一起行走或近战攻击。这时候玩家应该再按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.
        }
    }
}

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    您似乎有些混淆了您的条件。正如目前编写的那样,无论玩家攻击了多少次,只要Input.GetButtonUp ("Fire3") 为假(也就是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);
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多