Reputation: 25
I have made a timer script which starts timer when game starts. Thats fine, now what I want is when i press the "CurrentTime" button then the current time should be displayed on UI Text. For example game has started at "24:00" and after 4 minutes of play when I press the "CurrentTime" button then UI Text should display "24:04. Any help? here is my code.
public class Timer : MonoBehaviour {
public int Hours = 0;
public int Minutes = 0;
public Text m_text;
private float timestart;
public Text ending;
void Awake()
{
timestart = GetInitialTime();
}
void Start () {
m_text.text = timestart.ToString();
}
private void Update()
{
if (timestart > 0f)
{
// Update countdown clock
timestart += Time.deltaTime * 0.25f;
Hours = GetLeftHours();
Minutes = GetLeftMinutes();
// Show current clock
if (timestart > 0f)
{
m_text.text = Hours + ":" + Minutes.ToString("00");
}
else
{
// The countdown clock has finished
m_text.text = "00:00";
}
}
ending.text = Hours + ":" + Minutes.ToString("00");
}
private float GetInitialTime()
{
return Hours * 60f + Minutes;
}
private int GetLeftHours()
{
return Mathf.FloorToInt(timestart / 60f);
}
private int GetLeftMinutes()
{
return Mathf.FloorToInt(timestart % 60f);
}
}
Upvotes: 0
Views: 1546
Reputation: 90759
If you actually wanted the current real time it doesn't depend on the time the app was started but rather the system time itself.
Then all you need to do would be simply using System.DataTime
and in particular DateTime.Now
like
using System;
public class Timer : MonoBehaviour
{
public Text m_text;
public void GetCurrentTime()
{
var time = DateTime.Now;
m_text.text = $"{time.Hour:00}:{time.Minute:00}";
}
}
You wouldn't need the rest of your script at all because the system itself runs the time.
If what you rather want is a counter I would simply do something like
public class Timer : MonoBehaviour
{
public Text m_text;
public float Seconds;
public int Hours;
public int Minutes;
private void Start()
{
// in case you want to start the timer automatically
StartTimer();
}
public void StartTimer()
{
StopAllCoroutines();
StartCoroutine(TimerRoutine());
}
public void StopTimer()
{
StopAllCoroutines();
GetCurrentTime();
}
private IEnumerator TimerRoutine()
{
Seconds = 0;
Hours = 0;
Minutes = 0;
while(true)
{
Seconds += Time.deltaTime;
if(Seconds >= 60)
{
Seconds -= 60.0f;
Minutes += 1;
if(Minutes >= 60)
{
Minutes -= 60;
Hours += 1;
}
}
GetCurrentTime();
yield return null;
}
}
public void GetCurrentTime()
{
m_text.text = $"{Hours:00}:{Minutes:00}:{Seconds:00}"
}
}
Upvotes: 1