Hello guys,
I implemented a Timer like this: using UnityEngine;using UnityEngine.UI;using System.Collections;public c - Pastebin.com
And it works well. Now I want that when the player hits a trigger collider with a specific tag, seconds pass by (as you can see in LoseTime function). The trigger works, seconds goes down, but it is bugged:
let’s say that secLost is 5 and the timer when the player hits the trigger is 1:03 (one minute and 3 seconds). the timer should go to 00:58. Instead I see the timer that goes -00:05 (minus 5 seconds) and after some frames it goes 00:59 (that’s because in the update I wrote seconds = 59 when minutes is <= 0, but I don’t know how to find the solution of this problem of setting the seconds dynamically).
Have you got some ideas on how to implement it?
Thank you in advance!
There are 1000 milliseconds in a second and Time.deltaTime returns the number of seconds since the last frame.
I changed the variable “miliseconds” to “centiseconds”. But how do I get rid of that bug?
Changing a variable name doesn’t do anything. You don’t need half the code you have though as C# already has functions to deal with time for us.
using System;
using UnityEngine;
public class Countdown : MonoBehaviour
{
public float CountdownTimerInSeconds;
void Update()
{
CountdownTimerInSeconds -= Time.deltaTime;
}
private void OnGUI()
{
GUI.Label(new Rect(10, 10, 150, 50), FloatToTime(CountdownTimerInSeconds));
}
private string FloatToTime(float seconds)
{
var span = TimeSpan.FromSeconds(seconds);
return string.Format("{0}:{1:00}:{2:00}", span.Minutes, span.Seconds, span.Milliseconds);
}
}
2 Likes
Thank you for that! With a little bit of modification of your code i solved my problems!