I want to create a countdown timer in a Unity game I am creating. Up until now my game was running for a specific time but I was using InvokeRepeating
to end the game after the set time.
But now I want to display the time left in a GUI text. One approach could be to use InvokeRepeating
again but this time call it every second to decrement the timer. With this approach though it would mean do extra calculations for when a minute passes in order to display time appropriately and not just display the whole time in seconds.
Is there a different approach? Does Unity have any timers built in? Also which is the more efficient method?
Answer
Alternatively, you could use System.Timers.Timer which is probably the most performant of any solution. The following example shows a countdown for 100 seconds.
System.Timers.Timer LeTimer;
int BoomDown = 100;
void Start ()
{
//Initialize timer with 1 second intervals
LeTimer = new System.Timers.Timer (1000);
LeTimer.Elapsed +=
//This function decreases BoomDown every second
(object sender, System.Timers.ElapsedEventArgs e) => BoomDown--;
}
void Update ()
{
//When BoomDown reaches 0, BOOM!
if (BoomDown <= 0)
Debug.Log ("Boom!");
}
No comments:
Post a Comment