Problem with Timer

Hi all,

i am trying to set up a 20 minute count down timer but i am having trouble resetting the timer back to 20, right now it is set up to count down to 19 then add 1 minute when completed but it is returning “Resetting” in the console every cycle and not applying the changes to TwentyMinTimer. What am i missing here?

Thanks in advance for your help.

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

public class Timer : MonoBehaviour
{
    private float startTime;
    public string countDownTimer;
    private int TwentyMinTimer;
    private int SecondsCounterDown;

    void Start()
    {
        DontDestroyOnLoad(this.gameObject);
        startTime = Time.time;
        InvokeRepeating("TimeSinceStart", 0.01f, 1.0f);

    }

    public void TimeSinceStart()
    {
        float t = Time.time - startTime;

        int minutesInt = (int)t / 60;
        int SecondsInt = (int)t % 60;

        TwentyMinTimer = 20 - minutesInt;
        SecondsCounterDown = 59 - SecondsInt;

        print(TwentyMinTimer + ":" + SecondsCounterDown);

        if (TwentyMinTimer > 19)
        {
            TwentyMinTimer = TwentyMinTimer + 1;
            print("Resetting");
            //add life
        }

    }

}

sorry some parts of the code is named poorly, work in progress.

i manager to work it out, realized my < was not a > and also changed

if (TwentyMinTimer > 19)
        {
            TwentyMinTimer = TwentyMinTimer + 1;
            print("Resetting");
            //add life
        }

for

        if (TwentyMinTimer < 19)
        {
            startTime = Time.time;
        }
1 Like

Rather than Time.time - timeStart you can also increment Time.timeDelta.

float timeSpend += Time.timeDelta

Also rather than to that minute / second calculation in your update you do that on start :

int timeEnd = 60 * 20; // for a 20 min game

And then from your update :

void LateUpdate()
{
       timeSpent += Time.deltaTime;
       if (timeSpend >= timeEnd)
       {
            // game over
       }
}