Timer to run over multiple levels

Thank you for your help on my previous issue and now I have another. I have decided that rather than having a timer per level of my game, I’d like to have an overall timer and that picking up coins scattered through the scenes increases the amount of time you have. I have tried using DontDestroyOnLoad, but I seem to be resetting the timer to its initial start time, rather than carrying on the same timer and I don’t know how to get around it. The code I have is very long for what I’m sure is a simple, tight operation in anyone else’s game, but here it is, for what it’s worth:

function Awake () {
        DontDestroyOnLoad (this);
       	clockFGMaxWidth = clockFG.width;

    }

var clockIsPaused : boolean = false;
static var startTime : float; //(in seconds)
var timeRemaining : float; //(in seconds)
var percent : float; //for bar clock
var clockBG : Texture2D; //for bar clock
var clockFG : Texture2D; //for bar clock
var clockFGMaxWidth : float;  //starting width of the FG bar for bar clock
var nextLevel : int;

function Start()
{
	startTime = 600.0; //time for the whole game
}
function Update() {
	if (!clockIsPaused)
	{
		// make sure the timer is not paused
		DoCountdown();
	}
}

function DoCountdown() 
{
	timeRemaining = startTime - Time.timeSinceLevelLoad ;
//	Debug.Log("time remaining = " + timeRemaining);
	percent = timeRemaining/startTime * 100; //for bar clock
	if (timeRemaining < 0)
	{
		timeRemaining = 0;
		clockIsPaused = true;
		TimeIsUp();
	}
	ShowTime();
}

function PauseClock()
{
clockIsPaused = true;
}

function UnpauseClock()
{
clockIsPaused = false;
}

I figure that adding time isn’t going to be too hard, I just need to add to my startTime variable, right?

B

Your problem is this:

  timeRemaining = startTime - Time.timeSinceLevelLoad ;

You need the time since the game began (not the level loaded) - also you want to pause that time (which the current code won’t do)

You could certainly use InvokeRepeating as @Fattie says - it would be cleaner. In your existing code you need to count down then startTime when the clock isn’t paused.

function Start()
{
    startTime = 600.0; //time for the whole game
    timeRemaining = startTime;
}

function DoCountdown() 
{
    timeRemaining -= Time.deltaTime;
//  Debug.Log("time remaining = " + timeRemaining);
    percent = timeRemaining/startTime * 100; //for bar clock
    if (timeRemaining < 0)
    {
       timeRemaining = 0;
       clockIsPaused = true;
       TimeIsUp();
    }
    ShowTime();
}