rabidus-test/Assets/Scripts/vTimerCounter.cs

91 lines
1.9 KiB
C#
Raw Permalink Normal View History

2023-07-24 16:38:13 +03:00
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
2023-08-15 17:38:54 +03:00
public class vTimerCounter : MonoBehaviour, ITextChangable
2023-07-24 16:38:13 +03:00
{
public bool startTimerOnStart = false;
private bool started = false;
2023-08-15 17:38:54 +03:00
public UnityEvent<object> OnTextChange => _OnTextChange;
public UnityEvent<object> _OnTextChange = new UnityEvent<object>();
2023-07-24 16:38:13 +03:00
DateTime StartTime;
2023-08-22 17:17:54 +03:00
public UnityEvent OnTimeEnded;
2023-10-31 13:10:14 +03:00
public float LowTime = 10;
public UnityEvent<float> OnLowTime;
2023-08-22 17:17:54 +03:00
private UIPopupController _UIPopupController;
private void Awake()
{
_UIPopupController = FindObjectOfType<UIPopupController>();
}
2023-08-15 17:38:54 +03:00
2023-07-24 16:38:13 +03:00
public int Seconds;
public void Start()
{
if (startTimerOnStart) StartTimer();
}
public void StartTimer()
{
StartTime = DateTime.Now.AddSeconds(Seconds);
started = true;
}
private string lastText;
2023-08-15 17:38:54 +03:00
2023-07-24 16:38:13 +03:00
public void AddTime(int seconds)
{
if (!started)
return;
2023-08-22 17:17:54 +03:00
_UIPopupController.SpawnPopup(seconds.ToString(), UIMagnetType.Time);
2023-07-24 16:38:13 +03:00
StartTime = StartTime.AddSeconds(seconds);
}
private void Update()
{
if (!started)
return;
var time = DateTime.Now;
if (time > StartTime)
{
started = false;
2023-08-15 17:38:54 +03:00
OnTimeEnded?.Invoke();
2023-10-31 13:10:14 +03:00
lastText = $"{0:D2}:{0:D2}.<size=60%>{0:D3}";
2023-08-15 17:38:54 +03:00
_OnTextChange?.Invoke(lastText);
2023-07-24 16:38:13 +03:00
return;
}
var timeSpan = StartTime - time;
var ms = timeSpan.Milliseconds;
var sec = timeSpan.Seconds;
var min = timeSpan.Minutes;
2023-10-31 13:10:14 +03:00
if (timeSpan.TotalSeconds < LowTime)
{
OnLowTime?.Invoke(1);
}
else
{
OnLowTime?.Invoke(0);
}
lastText = $"{min:D2}:{sec:D2}.<size=60%>{ms:D3}";
2023-08-15 17:38:54 +03:00
_OnTextChange?.Invoke(lastText);
2023-07-24 16:38:13 +03:00
}
2023-10-02 19:12:35 +03:00
public void StopTimer()
{
started = false;
}
2023-07-24 16:38:13 +03:00
}