Madame Green Pea
Madame Green Pea

Reputation: 187

How to create a time penalty with coroutine in Unity?

I am working on a 2D game in Unity. The game is limited to 60 seconds. I would like to have a time bomb which causes time reduction when the player hit the bomb.

In my script, I have a boolean which is named as "hitDetect" and I use a Coroutine() for the countdown.

I tried to push the bomb to the right side when the player hit the bomb and then check whether the collision takes place with these codes:

void OnCollisionEnter2D(Collision2D bombcol)
{
    if(bombcol.gameObject.tag == "Enemy")
    {
        bombcol.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.right * hitForce);
    }
    hitDetect = true;
}

This is my Coroutine() function which provides me to have a game which is successfully limited to 60 seconds except for the time penalty:

IEnumerator LoseTime()
{
    while (true) {
        yield return new WaitForSeconds (1);
        timeLeft--; 
        if (hitDetect == true)
        {
            timeLeft= timeLeft - 5;
        }
    }
}

I also set the "hitDetect" as false in the start body.

void Start () 
    {
        StartCoroutine("LoseTime");
        hitDetect = false;
    } 

However, these methods don't lead me to success. When the player hit the bomb, time penalty doesn't work. Where is my mistake? What would you recommend?

Upvotes: 0

Views: 226

Answers (1)

dome12b
dome12b

Reputation: 623

I would recommend to calculate the time in the Update() function. So you can be sure the hitDetect is observed every frame and the penalty is set only once if you reset hitDetect after subtracting the penalty.

public bool hitDetect = false;
public float timeLeft = 60.0f;
public float penaltyTime = 5.0f;

void Start(){
    timeLeft = 60.0f;
    hitDetect = false;
}

void Update(){
    timeLeft -= Time.deltaTime;
    if(hitDetect){
        timeLeft -= penaltyTime;

        // reset the hit!
        hitDetect = false;
    }

    if(timeLeft < 0.0f){
        // end game?
    }
}

With this code your time is subtracted once by the penalty value if hitDetect is set true by your collision.

Hope this helps!

Upvotes: 5

Related Questions