2017-02-01 57 views
0

我目前正在Unity的遊戲中工作,無法完成任務。我需要它,當輸入按x次(近戰攻擊)時,角色停止工作,直到你按下另一個按鈕x次,即10次。玩家應該能夠攻擊3次,但是當他這樣做時,角色進入「假死」狀態,在那裏他不能再與玩家走路或近身攻擊。那時候玩家應該再次擊中另一個關鍵,然後玩家將能夠再次走近近戰攻擊。我認爲我可以通過一個簡單的if和else語句來實現這一點,但迄今爲止還沒有得到它的效果。出於某種原因,我的其他部分立即執行,而不是使用近戰攻擊5次。當輸入被按下x次時

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

回答

3

看來你已經混淆了你的條件。正如當前寫的,無論玩家多少次遭到攻擊,只要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); 
    } 
} 

希望這有助於!如果您有任何問題,請告訴我。

相關問題