Why is my timer ticking twice?

I wanted to make a countdown timer using a coroutine, but for some reason something goes wrong when the coroutine is running.

I have a TimeManager class which does the counting.

using UnityEngine;
using System.Collections;

public class TimeManager : MonoBehaviour 
{
    public static TimeManager use;

    int count = 30;
    public int Count
    {
        get
        {
            return count;
        }
    }


    void Awake()
    {
        if (use != null)
            GameObject.Destroy(use);
        else
            use = this;

        DontDestroyOnLoad(this);
    }

    public void SetTimer(int seconds)
    {
        count = seconds;
    }

    public void StartTimer()
    {
        StartCoroutine(Countdown());
    }

    IEnumerator Countdown()
    {
        while (count >= 0)
        {
            yield return new WaitForSeconds(1f);
            count--;

            Debug.Log(count);
        }
    }
}

And then I start the counter from my StartLevel script

using UnityEngine;
using System.Collections;

public class StartLevel : MonoBehaviour
{    
	void Start () 
    {
        TimeManager.use.SetTimer(120);
        TimeManager.use.StartTimer();
	}
}

The debug output from the TimeManager always shows 2 ticks per second. So it shows

119
118
<Wait a second>
117
116
<Wait a second>
115
114
<And so on...>

and I don’t understand why.

Any idea as to why it decrements count twice every time?

Make sure your Coroutine is called only once per second and not once every update. You can do a simple loop with a “cooldown” and then a reset variable.

You can set the reset variable (float reset, for example) to 1 second (float reset = 1;). In your update function, you can use:

void Update() {

  while(!countdown <=0) {
    //Do Coroutine Stuff Here
  }
  else
    countdown -= Time.deltaTime;

}

The while statement makes sure it’s only called every second.

My bad, this error doesn’t happen in an empty scene. So went through my scene again and sure enough, the StartLevel script was attached to another object so TimeManager was called twice at the beginning of the level.

Also, my buddy Kasper suggested I change the way I make the singleton without relying on DontDestroyOnLoad().

private static TimeManager instance = null;
public static TimeManager use
{
    get
    {
        if (instance == null)
            instance = (TimeManager)FindObjectOfType(typeof(TimeManager));
        return instance;
    }
}