How do I make a lap timer?

I’m making a racing game for a school project and I need to have a timer that counts upward from start until the player crosses the finish line. I also need the timer to go back a certain increment when the player hits an object (i.e. +Time) and then go forward when the player collides with an object like a barricade. Please help!

I figured out the timer code:

private var timerText:GUIText;

private var startTime:float = 0         
    
function Update () {
    
    timerText = gameObject.GetComponent(GUIText);
    
    timeTaken = startTime + Time.time;
    
    timerText.text = FormatTime (timeTaken);
    
    }           
    
function FormatTime (time : float){
    
    var minutes : int = Mathf.Floor(time / 60.0);
    
    var seconds : int = Mathf.Floor(time - minutes * 60.0);
    
    var milliseconds = time - Mathf.Floor(time);
    
    milliseconds = Mathf.Floor(milliseconds * 1000.0);
    
    var sMinutes = "00" + minutes.ToString();
    
    sMinutes = sMinutes.Substring(sMinutes.Length-2);
    
    var sSeconds = "00" + seconds.ToString();
    
    sSeconds = sSeconds.Substring(sSeconds.Length-2);
    
    var sMilliseconds = "000" + milliseconds.ToString();
    
    sMilliseconds = sMilliseconds.Substring(sMilliseconds.Length-3);
            
    timeText = sMinutes + ":" + sSeconds + ":" + sMilliseconds;
        
    return timeText;
    
        }

Now I just have to figure out how to add or subtract time depending on which object the player collides with. Thanks

2 Answers

2

If you have not started running or finished the race is false, no counting. The rest of the time timer is increased at a rate of 1 per second. If you enter a trigger that is a counter up then you decrease the counter.

var timer:float;
var running:boolean = false;
function Update(){
   if(!running)return;
   timer += Time.deltaTime;
}

function OnTriggerEnter(col:Collider){
   if(col.gameObject.CompareTag("CounterUp"))timer -= value;
   else if (col.gameObject.CompareTag("EndRace")) running = false;
}

So, this would be a new script attached to my game objects that the racer could collide with?

That could be using the GUI you have on the example. Only the logic is somehow modified. You would have to use some trigger boxes that represent checkpoint and a final trigger for the end race. And this is attached to the racing object not the boxes

Where is it happening?

It happens on startup.

No, the error, where is it? The line?

Any other suggestions?