Timer class

Hey, I pulled this Timer class from the net.

using System;


public class Timer 
{
    
    private DateTime startTime;
    private DateTime stopTime;
    private bool running = false;

    
    public void Start() 
    {
        this.startTime = DateTime.Now;
        this.running = true;
    }


    public void Stop() 
    {
        this.stopTime = DateTime.Now;
        this.running = false;
    }


    // elaspsed time in milliseconds
    public double GetElapsedTime() 
    {
        TimeSpan interval;
        
        if (running) 
            interval = DateTime.Now - startTime;
        else
            interval = stopTime - startTime;
            
        return interval.TotalMilliseconds;
    }
    
   
    // elaspsed time in seconds
    public double GetElapsedTimeSecs() 
    {
        TimeSpan interval;
        
        if (running) 
            interval = DateTime.Now - startTime;
        else
            interval = stopTime - startTime;
            
        return interval.TotalSeconds;
    }
}

What I’m trying to achieve is start the camera at the beginning of a level, wait 90 seconds, then end the level (move on to the next one).

This is my attempt:

using UnityEngine;
using System.Collections;

public class EndLevel : MonoBehaviour
{
	private int TimeUntilEnd;
	private Timer timer;
	
	void Start()
	{
		timer = new Timer();
		
	}
	
	// Update is called once per frame
	void Update ()
	{
		if( Application.loadedLevel == 1)
		{
			System.Console.WriteLine(timer.GetElapsedTimeSecs());
			timer.Start();
			TimeUntilEnd = 90;
			if( timer.GetElapsedTimeSecs() >= TimeUntilEnd )
			{
				// Test
				Debug.Log("Time's up!");
                                //blah blah, load level, and do other stuff
			}
		}
	}
}

Obviously, it doesn’t work. The line Console.WriteLine() line prints out some really odd info…

Obviously, that’s not right. Is there an obvious problem in this timer, or can some provide another way to do this?

Thanks!

How about you just do:

function Start() {
     yield WaitForSeconds(90);
    //blah blah, load level, and do other stuff 
}

–Eric

I’m with Eric, just use a yield statement. But going with you for a minute and looking at your code, I notice that you call timer.Start() every frame:

// Update is called once per frame
void Update ()
{
  if( Application.loadedLevel == 1)
  {
    System.Console.WriteLine(...);
    timer.Start();
    ...

So no wonder you’re always seeing such short elapsed times as you’re essentially only tracking the time since the very last frame. Either change your code so you only call timer.Start() once or just go with a yield statement, that’s why they are there.

Doh… You’re totally right. I should start it in the Start function… Anyways, I switched to using yield, and just used OnLevelLoaded(). Thanks guys!
(I always have problem with putting time based “stuff” in the Update function >.<) :lol: