rabidus-test/Assets/Scripts/vTimerCounter.cs

91 lines
1.9 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;
public float LowTime = 10;
public UnityEvent<float> OnLowTime;
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}.<size=60%>{0:D3}";
_OnTextChange?.Invoke(lastText);
return;
}
var timeSpan = StartTime - time;
var ms = timeSpan.Milliseconds;
var sec = timeSpan.Seconds;
var min = timeSpan.Minutes;
if (timeSpan.TotalSeconds < LowTime)
{
OnLowTime?.Invoke(1);
}
else
{
OnLowTime?.Invoke(0);
}
lastText = $"{min:D2}:{sec:D2}.<size=60%>{ms:D3}";
_OnTextChange?.Invoke(lastText);
}
public void StopTimer()
{
started = false;
}
}