Simple Timer Class

From Unify Community Wiki
Revision as of 15:06, 5 September 2009 by PsychicParrot (Talk | contribs)

Jump to: navigation, search

by [1] psychicparrot


Save the script below as 'Timer.cs'

Timer timerRef=new(Timer); // <--creates instance of the timer class

timerRef.startTimer(); // <- kick things off(!)

timerRef.stopTimer(); //<- pause time

timerRef.resetTimer(); // <- reset time to zero

timerRef.getFormattedTime() - returns formatted string


A simple timer class, with standard game-like time string formatting!

<csharp> // SIMPLE TIMER CLASS // by Psychicparrot - // // Usage: timerRef.startTimer() - kick things off(!) // timerRef.stopTimer() - pause time // timerRef.resetTimer() - reset time to zero // timerRef.getFormattedTime() - returns formatted string // // TODO: Counting down as well as up! //

using UnityEngine;

public class Timer : MonoBehaviour {

private float timeElapsed; private float timeCounter; private float lastTime;

private bool isTimerRunning; private float timeScaleFactor=1f; // <-- If you need to scale time, change this! private float currentTime;

public void Start () {

// do setup on the timer as soon as this script is created - setup also has a call to startTime() // so time will start as soon as this is called. startTime();

// if you wanted a delay before the timer kicks in (say you want to wait until after a fade in // or something) you could just invoke it in x seconds like this: // Invoke("startTime",4);


// Update is called once per frame public void doUpdate () {


if(this.isTimerRunning){ this.timeCounter=this.timeCounter+this.timeElapsed*this.timeScaleFactor; }

currentTime=this.timeCounter; lastTime=Time.time;


public void setupTimer(){

this.timeElapsed=0f; this.lastTime=0f; this.timeCounter=0f; this.currentTime=0f; this.lastTime=Time.time; this.isTimerRunning=true;


public void startTime(){ this.isTimerRunning=true; this.lastTime=Time.time; }

public void stopTime(){ this.isTimerRunning=false; }

public void resetTime(){ this.timeElapsed=0f; this.lastTime=0f; this.timeCounter=0f; this.currentTime=0f; this.lastTime=Time.time; }

public float getTime(){ return timeCounter; }

public string getFormattedTime(){

// grab minutes int aMinute=(int)currentTime/60;

// grab seconds int aSecond=(int)currentTime%60;

// grab milliseconds float aMillis=(currentTime*1000); aMillis=(int)aMillis%99;

// format string into mm:ss:mm string seconds=aSecond.ToString(); if(seconds.Length<2) seconds="0"+seconds;

string minutes=aMinute.ToString(); if(minutes.Length<2) minutes="0"+minutes;

string mills=aMillis.ToString(); if(mills.Length<2) mills="0"+mills;

string timeString=minutes+":"+seconds;

return timeString; }

} </csharp>

Personal tools