Two timers out of sync

I made a test project which you can clone on Github, and documented my issue here.

In essence the problem is that I have two timers; one that counts down from 70 seconds to 0 (and then starts all over again), and the second one just shows the current client time.

Problems which I have are the following:

  1. If you open up any other window you will notice that the timer will stop, and continue counting once you return to the Unity window
  2. TimerText and TimeText are not “ticking off” at the same time

If someone has hints on how to approach solving this, I would be very grateful.

For reference, my code is this:

#pragma strict

var timer: float = 70;
var isFinishedLevel : boolean = false;
public var displayText : UnityEngine.UI.Text;
public var timeText : UnityEngine.UI.Text;

private var oldTimer : float;

function Start(){
	oldTimer = timer;
}

function Update()
{
	if (!isFinishedLevel) {
		timer -= Time.deltaTime;
	} 

	if (timer > 0) {
		var minsDisplay : String = parseInt( timer / 60 ).ToString();
		var secsDisplay : String = parseInt( timer ).ToString();
		 
		if ( (timer - ( parseInt(minsDisplay) * 60)) > 10 ) {
		     secsDisplay = parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString();
		} 
		else {
			secsDisplay = "0" + parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString();
		}
		
		displayText.text = minsDisplay + " : " + secsDisplay;
	} 
	else {
	 	timer = oldTimer;
	}
	
	CurrentTime();
}

function CurrentTime() { 
	var dt : System.DateTime = System.DateTime.Now;
	var h : int = dt.Hour; 
	var m : int = dt.Minute; 
	var s : int = dt.Second;

	timeText.text = h + ":" + m + ":" + s;
}

Number 1 is intended behaviour. For 2 I only see TimeText

@meat5000: Thanks - do you know how do I get around it then? Someone must have stumbled upon a similar problem, but can't seem to find it.

Edit -> Project Settings -> Player -> Run In Background

Great, thank you!, please put this as an answer so I can accept it. Oh, and if you don't mind, can you shed some light on #2?

I don't see TimerText in your script :) Did you mean displayText?

1 Answer

1

timeText is updated with system time. If you want them to tick the same, displayText needs to update with a trigger from that.

The text ‘tickrate’ is the same. They are simply receiving new information at different times.

Part 2) Another problem is that you cut off fractional seconds when the 70 seconds are passed. Instead of timer = oldTimer; do timer += oldTimer; This will preserve the fractional part from the last interval.

There ya go :) Got you started.

Thanks - upvoted as promised ;)