Graphics Reference
In-Depth Information
// store the current time so that we can use it on the next
// update
lastTime=Time.realtimeSinceStartup;
}
The rest of the function checks to see whether isTimerRunning is true before updat-
ing currentTime. isTimerRunning is a Boolean that we can use to start or stop the timer
without affecting anything else.
Note that one commonly used method of pausing Unity games is to set Time.timeScale to 0,
which would stop a timer that didn't use Time.realtimeSinceStartup. In this case, we will be
unaffected by timescale, so this alternative system will need to be used to start and stop the
timer during a game pause.
The final part of the UpdateTimer() function grabs the current Time.realtimeSince-
Startup and stores it in the variable lastTime, so that we can use its value to calculate the
time elapsed between this and the next call to UpdateTimer.
A StartTimer() function is used to start the timer:
public void StartTimer ()
{
// set up initial variables to start the timer
isTimerRunning=true;
lastTime=Time.realtimeSinceStartup;
}
isTimerRunning tells us whether or not to update currentTime in the UpdateTimer()
function shown earlier. When the timer starts, we need to ensure that its value is true.
lastTime needs to be reset when we start the timer so that time will not be counted
that occurred 'in between' the timer being stopped and the timer starting up again.
public void StopTimer ()
{
// stop the timer
isTimerRunning=false;
}
isTimerRunning is set to false, which stops UpdateTimer() from adding any extra time to
the currentTime variable.
If there is ever a need to reset the timer, we need to refresh some of the main variables
to their default states. In the ResetTimer() function, timeElapsed, lastTime, and currentTime
are reset:
public void ResetTimer ()
{
// resetTimer will set the timer back to zero
timeElapsed=0.0f;
currentTime=0.0f;
lastTime=Time.realtimeSinceStartup;
}
Search WWH ::




Custom Search