- Home /
Is there a timer that can start when game starts and stops when the game ends in Javascript?
Is there a way where I can have timer start when a button is clicked and stops when the game ends in Javascript with this code? That way, when the player starts the game then ends it, they can see how long it took them to finish the game.
#pragma strict
private var startTime : float;
var textTime : String;
function Start() {
startTime = Time.time;
}
function OnGUI () {
var guiTime = Time.time - startTime;
var minutes : int = guiTime / 60;
var seconds : int = guiTime % 60;
var fraction : int = (guiTime * 100) % 100;
textTime = String.Format ("{0:00}:{1:00}:{2:00}", minutes, seconds, fraction);
GetComponent(GUIText).text = textTime;
}
Answer by hoy_smallfry · Jul 11, 2013 at 05:00 PM
You can use C#'s System.Diagnostics.Stopwatch class. There are examples at the bottom of the link on how it's used. You would just need to start it when the button is clicked in your OnGUI and end it whenever your game ends. Then just used the Elapsed member to get the number of seconds between start and stop.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Coding A Tornado Particle Effect 0 Answers
How can I make a "Fastest Lap" scoring system for a racing game? 2 Answers
Laptime timer using TimeSpan - force milliseconds to 00 and not 000? 1 Answer
I need help with scripting 0 Answers