CountDown timer in unity

Updated on June 13, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
8 on June 13, 2017

Hello everyone !

i was trying to make a count down that starts from 40.00 secondes down to 0 but when i press play the countdown starts at 39.98 and when i die and press play again the countdown goes to 39.97 and i dont want that i want it to start from 40.00 down to 0 im using this script

using UnityEngine;
using UnityEngine.UI;
public class CountDown : MonoBehaviour
{
    public Text countdowntext;
    float _countDownTimeLeft = 40.0f;
    
    void Update()
    {
        _countDownTimeLeft -= Time.deltaTime;
        
        countdowntext.text = _countDownTimeLeft.ToString("f2");
    }
   
}
  • Liked by
Reply
2 on June 13, 2017

Try changing:

_countDownTimeLeft -= Time.deltaTime;

to

_countDownTimeLeft -= 1 * Time.deltaTime;
Guru
on June 13, 2017

Ehh, why?

 

Guru
on June 13, 2017

Well.. apparently I thought wrong. 

Let’s add another reason to my list of reasons as to why I should probably start with Unity again.

Show more replies
  • Liked by
Reply
Cancel
2 on June 13, 2017

You should probably use

countdowntext.text = Mathd.RoundToInt(countDownTimeLeft).ToString();

 

on June 13, 2017

i want to keep the numbers after the , its looks more cool like that :p

 

Guru
on June 13, 2017

Ok, what you can then do is subtract the deltatime after you update the text. Then it should start at 40.

 

Show more replies
  • Liked by
Reply
Cancel
1 on June 13, 2017

After you press play, a small amount of time passes (0.02 seconds in this case), it does start from 40, the script is working correctly.

on June 13, 2017

So how can i fix it ! I have the same probleme 🙁

Show more replies
  • Liked by
Reply
Cancel