[CodeSample] Countdown Timer

Hi guyz,
I’ve been searching some countdown methods with c# in forum but cant find complete one.

And mine is complete now. Small thing but wanted to share…

Hope help someone… :slight_smile:

In my usage i attached that to my vehicle and and checked ‘canStart’ variable before apply throttle to wheels.

using UnityEngine;
using System.Collections;


public class CountDownBeforeStart: MonoBehaviour
{
    public bool canStart = false;
    public AudioSource AudioPlayer;
    public AudioClip BipCount;
    public AudioClip BipStart;
    public float CountDownFrom = 5;
    private bool _isCounting = false;

    void Start()
    {
        if (CountDownFrom > 0)
        {
            CountDown();
        }
    }
    
    void CountDown()
    {
        if (!_isCounting)
        {
            StartCoroutine(Wait());
        }
    }

    IEnumerator Wait()
    {
        _isCounting = true;
        for (float i = CountDownFrom; i >= 0; i--)
        {
            Debug.Log(i);
            if (i == 3||i== 2||i== 1)
                PlayAudio(BipCount);
            else if (i== 0)
            {
                PlayAudio(BipStart);
                canStart= true;

            }
            yield return new WaitForSeconds(1);
        }
        
        _isCounting = false;
    }

    
    void PlayAudio(AudioClip Clip)
    {
        AudioPlayer.clip = Clip;
        AudioPlayer.loop = false;
        AudioPlayer.Play();
        Debug.Log("Playing " + Clip.name);

    }
}

I just used this sample for my game waves system. It worked beautifully. Nicely done.

I wrote one similar, like this

    public int CountDownTime = 10;

    private int CountTime = 0;

 void StartCountDown()
    {
        if (this.CountTime > 0 || this.IsInvoking("CountDownTimer"))
        {
            return;
        }
        this.CountTime = this.CountDownTime;
        this.InvokeRepeating("CountDownTimer", 0f, 1f);
    }

     void CountDownTimer()
    {
        if (CountTime <= 0)
        {
            //Do finale
            this.CancelInvoke("CountDownTimer");
        }
        else
        {
            CountTime--;
            //Do something every second

        }
    }

bool IsCountingDown(){
    return this.IsInvoking("CountDownTimer");
}

thanks so much i could not find a working one to until i see this

This is great, thanks a lot!! …for something so seemingly simple, it’s really not…
Unity has great script references but the waitforseconds example is well…only HALF of what you apparently need, aka USELESS…

…threw me for a loop with the “i”, cause i’m a noob, but now I feel like Im walking away with 2 valid lessons :slight_smile:
Thanks again!!