Pro_Unit

OnTicksTimer

Dec 21st, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. using UnityEngine;
  6. using UnityEngine.Events;
  7.  
  8. namespace GameCore
  9. {
  10.     public class OnTicksTimer : MonoBehaviour
  11.     {
  12.         [SerializeField] UnityEvent OnStartTimer;
  13.         [SerializeField] UnityEventInt OnTickTimer;
  14.         [SerializeField] UnityEvent OnEndTimer;
  15.         [SerializeField] int Seconds;
  16.         public void StartTimer()
  17.         {
  18.             StartTimer(0);
  19.         }
  20.         public void StartTimer (int seconds = 0)
  21.         {
  22.             if (seconds != 0) Seconds = seconds;
  23.             OnStartTimer.Invoke ();
  24.             StartCoroutine (TickTimer ());
  25.         }
  26.  
  27.         private IEnumerator TickTimer ()
  28.         {
  29.             if (CheckComplete ()) yield break;
  30.             Seconds = Seconds.Abs (); // Seconds = Mathf.Abs(Seconds); // Is to need positive
  31.             WaitForSeconds wfs = new WaitForSeconds (1f);
  32.             while (Seconds > 0)
  33.             {
  34.                 yield return wfs;
  35.                 Seconds--;
  36.                 OnTickTimer.Invoke (Seconds);
  37.                 if (CheckComplete ()) yield break;
  38.             }
  39.  
  40.         }
  41.  
  42.         private bool CheckComplete ()
  43.         {
  44.             bool isZero = Seconds == 0;
  45.             if (isZero) OnEndTimer.Invoke ();
  46.             return isZero;
  47.         }
  48.     }
  49.     [Serializable] public class UnityEventInt : UnityEvent<int> { }
  50. }
Add Comment
Please, Sign In to add comment