I’m trying to get this timer script (which I got from the marble tutorial) to start, stop and reset at zero when certain things in the game happen, or when certain buttons on the keyboard are pressed. Any Ideas?
var startTime = 30.0;
function Update () {
// The time left for player to complete level!
timeLeft = startTime - Time.time;
// Don't let the time left go below zero.
timeLeft = Mathf.Max (0, timeLeft);
// Format the time nicely
guiText.text = FormatTime (timeLeft);
}
// Format time like this
// 12[minutes]:34[seconds].5[fraction]
function FormatTime (time)
{
var intTime : int = time;
var minutes : int = intTime / 60;
var seconds : int = intTime % 60;
var fraction : int = time * 10;
fraction = fraction % 10;
// Build string with format
// 12[minutes]:34[seconds].5[fraction]
timeText = minutes.ToString () + ":";
timeText = timeText + seconds.ToString ();
timeText += "." + fraction.ToString ();
return timeText;
}
For that you will maybe want to use deltaTime instead like this:
var timerLength = 60.0;
private var timer = 0.00;
private var activated = true;
function Update ()
{
if(activated) timer += Time.deltaTime; // if the timer is running, add the time that passed since last frame
// The time left for player to complete level! clamp between timer length and 0
timeLeft = Mathf.Clamp(timer - timerLength, 0, timerLength);
if(timeLeft == 0) TimeOut(); //we ran out of time
// Format the time nicely
guiText.text = FormatTime (timeLeft);
}
function TimeOut ()
{
// do stuff on time out
}
function StartTimer ()
{
activated = true;
}
function PauseTimer ()
{
activated = false;
}
function StopTimer ()
{
activated = false;
timer = 0;
}
function RewindTimer ()
{
timer = 0;
}
// Format time like this
// 12[minutes]:34[seconds].5[fraction]
function FormatTime (time)
{
var intTime : int = time;
var minutes : int = intTime / 60;
var seconds : int = intTime % 60;
var fraction : int = time * 10;
fraction = fraction % 10;
// Build string with format
// 12[minutes]:34[seconds].5[fraction]
timeText = minutes.ToString () + ":";
timeText = timeText + seconds.ToString ();
timeText += "." + fraction.ToString ();
return timeText;
}
You can also call the StopTimer() etc functions from anywhere else. an example is a timer controller script that calls functions in a referenced Timer every frame depending on key input.
Thanks for the script but how do I controll it? I’ve started the following script, what would be the rest? How do I call the StartTimer, PauseTimer, and StopTimer from another script?
function Update () {
if (Input.GetKey ("a"));