如何创建炸弹倒数计时器?

时间:2018-12-08 10:58:20

标签: c# unity3d

我正在制作一个使用炸弹和爆炸的Unity游戏。我想限制玩家只能每3秒植入1枚炸弹,第一个炸弹会爆炸,然后玩家可以植入另一个炸弹,为此我创建的计时器似乎无效。

当我玩游戏时,玩家可以放置炸弹,但等待3秒以上后无法再放置炸弹。我的时间逻辑是否正确?

public class CombatController : MonoBehaviour {

    //public GameObject enemy;
    [SerializeField]
    public GameObject Bomb;
    public GameObject Explosion;
    public int timer = 0;


    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        BombKeyPress ();   //Check if the user wants to plant the bomb.     
    }


    //Method BombKeyPress - This method will activate logic for our bombkeypress.
    public void BombKeyPress ()
    {

        if(Input.GetKeyUp(KeyCode.Space)) {
            BombDrop ();

        }

    }

    //Method BombDrop - This method will instantiate our bomb.
    private void BombDrop () 
    {
        //If the timer is not counting, allow the player to drop another.
        if (Bomb && timer <=0) {
            Instantiate (Bomb, this.gameObject.transform.position, Quaternion.identity); //Make New Bombs
            timer = 3; //Set our bomb timer to 3 seconds.

            //Countdown our bombtimer.
            for (int i = 3; i <= 0; i--) {
                timer = i;
                print(i);
            }

            //BombExplosion(); //Now blow up our bomb

        }   

    } 

}

2 个答案:

答案 0 :(得分:1)

您需要使用协程引爆炸弹,因此您可以编写类似以下内容的

//public GameObject enemy;
[SerializeField]
public GameObject Bomb;
public GameObject Explosion;
public float timer = 0;

private float currentTime;
private bool canBomb = true;


// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
        BombKeyPress ();   //Check if the user wants to plant the bomb.   
}
IEnumerator BombExplosionTimer()
{
    yield return new WaitForSeconds(timer);
    BombExplosion();
    canBomb = true;
}

public void BombExplosion()
{

    //Put your Bomb explosion logic here
}


//Method BombKeyPress - This method will activate logic for our bombkeypress.
public void BombKeyPress ()
{

    if(Input.GetKeyUp(KeyCode.Space) && canBomb) {
        canBomb = false;
        BombDrop ();
        StartCoroutine(BombExplosionTimer());
    }
}



//Method BombDrop - This method will instantiate our bomb.
public void  BombDrop () 
{
    //If the timer is not counting, allow the player to drop another.

        Instantiate (Bomb, this.gameObject.transform.position, Quaternion.identity); //Make New Bombs
        timer = 3; //Set our bomb timer to 3 seconds.

} 

答案 1 :(得分:1)

您可以使用Time类。很简单。

声明两个变量BombRateNextBombTime,如下所示:

[SerializeField]
private float BombRate=0.5f;// Tweak to value to your requirement.
private float NextBombTime=0f;

因此,在炸弹功能中,您可能会遇到类似这样的事情:

void Bomb (){
if(Time.time>NextBombTime){
NextBombTime=Time.time+BombRate;
//Do your bomb stuff here
}
}

如果愿意,您也可以使用协程。

我希望这会有所帮助。