Search Unity

Having trouble restarting a countdown timer using time.deltatime

Discussion in 'Scripting' started by gjuarez, Jan 20, 2020.

  1. gjuarez

    gjuarez

    Joined:
    Jul 17, 2018
    Posts:
    9
    Hi, please help. I've been having trouble with this problem for far too long.
    I'm having trouble restarting a countdown timer back to 30 seconds. It works the first time it counts down to 0 but afterward, when I try to restart it, it doesn't work.

    Here is my code:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.SceneManagement;

    public class CountdownTimer : MonoBehaviour
    {
    float currentTime;
    float startingTime = 30f;

    Vector2 restartPosition = new Vector2(0f, -9.25f);
    public GameObject player;
    public PlayerMovement PlayerMovement;
    [SerializeField]
    Text countdownText;
    public AudioSource froggerDied;

    public bool restartTime;

    // Start is called before the first frame update
    void Start()
    {
    currentTime = startingTime;
    }

    // Update is called once per frame
    void Update()
    {
    countdownText.text = currentTime.ToString("0");
    currentTime -= Time.deltaTime ;

    Debug.Log("currentTime = " + currentTime);

    if (currentTime > 5)
    {
    countdownText.GetComponent<Text>().color = Color.green;
    }
    if (currentTime < 5)
    {
    countdownText.GetComponent<Text>().color = Color.red;
    }
    if (currentTime <= 0)
    {
    player.transform.position = restartPosition;
    PlayerMovement.froggerLives -= 1;
    currentTime = startingTime;
    froggerDied.Play();
    }
    if (restartTime == true) //restartTime is called true in another script but this shouldn't be a problem
    {
    currentTime = startingTime;
    restartTime = false;
    }
    }
    }