rabidus-test/Assets/Scripts/vTimerCounter.cs

75 lines
1.7 KiB
C#

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public class vTimerCounter : MonoBehaviour, ITextChangable
{
public bool startTimerOnStart = false;
private bool started = false;
public UnityEvent<object> OnTextChange => _OnTextChange;
public UnityEvent<object> _OnTextChange = new UnityEvent<object>();
DateTime StartTime;
public UnityEvent OnTimeEnded;
private UIPopupController _UIPopupController;
private void Awake()
{
_UIPopupController = FindObjectOfType<UIPopupController>();
}
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;
_UIPopupController.SpawnPopup(seconds.ToString(), UIMagnetType.Time);
StartTime = StartTime.AddSeconds(seconds);
}
private void Update()
{
if (!started)
return;
var time = DateTime.Now;
if (time > StartTime)
{
started = false;
OnTimeEnded?.Invoke();
lastText = $"{0:D2}:{0:D2}:{0:D2}.<size=60%>{0:D3}";
_OnTextChange?.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}";
_OnTextChange?.Invoke(lastText);
}
}