Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.Events;
- public class Timer : MonoBehaviour
- {
- #region SINGLETON
- private static Timer _singleton;
- public static Timer Singleton
- {
- get
- {
- if (_singleton == null)
- {
- _singleton = GameObject.FindObjectOfType<Timer>();
- }
- return _singleton;
- }
- }
- #endregion
- public UnityEvent timeEvent;
- public float Seconds;
- public int Hours;
- public int Minutes;
- [SerializeField] private Text m_text;
- private bool eventIsOn = true;
- private void Start()
- {
- if (timeEvent == null)
- timeEvent = new UnityEvent();
- 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(IsDivisble((int)Seconds, 10))
- {
- if (eventIsOn == false)
- {
- timeEvent.Invoke();
- eventIsOn = true;
- }
- }
- else
- {
- eventIsOn = false;
- }
- 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}";
- m_text.text = $"Time: {Minutes:00}:{Seconds:00}";
- }
- /// <summary>
- /// Проверка на кратность одного числа на другое
- /// </summary>
- /// <param name="x">Исходное число</param>
- /// <param name="n"></param>
- /// <returns></returns>
- public bool IsDivisble(int x, int n)
- {
- return (x % n) == 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement