rabidus-test/Assets/Scripts/vTimerCounter.cs

62 lines
1.4 KiB
C#

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public class vTimerCounter : MonoBehaviour
{
public bool startTimerOnStart = false;
private bool started = false;
public event UnityAction<string> OnUpdateTimer;
DateTime StartTime;
public int Seconds;
public void Start()
{
if (startTimerOnStart) StartTimer();
}
public void StartTimer()
{
StartTime = DateTime.Now.AddSeconds(Seconds);
started = true;
}
private string lastText;
public void AddTime(int seconds)
{
if (!started)
return;
StartTime = StartTime.AddSeconds(seconds);
}
private void Update()
{
if (!started)
return;
var time = DateTime.Now;
if (time > StartTime)
{
started = false;
GameManager.Instance.ChangeState(GameState.Ended);
lastText = $"{0:D2}:{0:D2}:{0:D2}.<size=60%>{0:D3}";
OnUpdateTimer?.Invoke(lastText);
return;
}
var timeSpan = StartTime - time;
var ms = timeSpan.Milliseconds;
var sec = timeSpan.Seconds;
var min = timeSpan.Minutes;
var hour = timeSpan.Hours;
lastText = $"{hour:D2}:{min:D2}:{sec:D2}.<size=60%>{ms:D3}";
OnUpdateTimer?.Invoke(lastText);
}
}