Home > Back-end >  Repeating countdown timer unity
Repeating countdown timer unity

Time:10-07

I'm new to unity. My intention is to make a countdown timer start with 5 seconds and after it reached to zero I need to restart again from 5 repeatedly. Help me with this thank you. my current code:

private bool stopTimer;
[HideInInspector]public float time1;
private float deltaT;

void Start()
{
    stopTimer = false;
    timerSlider.maxValue = gameTime;
    timerSlider.value = gameTime;
    
}

// Update is called once per frame
public void Update()
{
    deltaT = Time.time;
    timerR();

}

public void timerR()
{
    time1 = gameTime - deltaT;
    Debug.Log(time1);
    int minutes = Mathf.FloorToInt(time1 / 60);
    int seconds = Mathf.FloorToInt(time1 - minutes * 60f);




    string textTime = string.Format("{0:0}:{1:00}", minutes, seconds);

    if (time1 <= 0)
    {
        stopTimer = true;
        

    }

    if (stopTimer == false)
    {
        timerText.text = textTime;
        timerSlider.value = time1;
    }
}

}

CodePudding user response:

In this web you have a simple timer: https://answers.unity.com/questions/351420/simple-timer-1.html Here my example code:

float actualtime=0; #Time in the coundownt that we have now
public float maxtime=5;
float actualtimedelta=0; 
string texTime
void Update()
{
    actualtime=Time.deltaTime-actualtimedelta

   if(actualtime>=5)
   {
     actualtimedelta=Time.deltatime
     textTime ="00:00";
   } 
  else
   { 
     actualtime= maxtime-actualtime;
     int seconds= Mathf.FloorToInt(actualtime);
     int miliseconds=Mathf.FloorToInt((actualtime -seconds)*100)
     texTime=  string.Format("{0:0}:{1:00}", seconds, miliseconds);
   }

  

}

CodePudding user response:

You can use the power of Coroutine and some handy C# classes like TimeSpan and Stopwatch, something like below code.

   using System;
   using System.Collections;
   using System.Diagnostics;
   using UnityEngine;
   using UnityEngine.UI;
    public class CountDown : MonoBehaviour
    {
        public Text text;
        public int secounds = 5;
        public int waitSecOnEachRound = 1;
        readonly Stopwatch timer = new Stopwatch();
        void Start()
        {
            StartCoroutine(CounDowntStarter());
        }
        IEnumerator CounDowntStarter()
        {
            TimeSpan timeStart = TimeSpan.FromSeconds(secounds);
            while (true)
            {
                timer.Restart();
                while (timer.Elapsed.TotalSeconds <= secounds)
                {
                    yield return new WaitForSeconds(0.01f);
                    timeStart = TimeSpan.FromSeconds(secounds - Math.Floor(timer.Elapsed.TotalSeconds));
                    text.text = string.Format("{0:00} : {1:00}", timeStart.Minutes, timeStart.Seconds);
                }
                yield return new WaitForSeconds(waitSecOnEachRound);
            }
        }
    }
  • Related