slimecing

a fighting game featuring slimes and swords
Log | Files | Refs | README

Timer.cs (1186B)


      1 using System;
      2 
      3 namespace Slimecing.Dependency
      4 {
      5     public class Timer
      6     {
      7         public int loopCount
      8         {
      9             get; private set;
     10         }
     11 
     12         public float remainingSeconds
     13         {
     14             get; private set;
     15         }
     16 
     17         public float initialRemainingSeconds
     18         {
     19             get; private set;
     20         }
     21 
     22         // Constructor will set local variables to the give arguments
     23         public Timer(float duration, int loops)
     24         {
     25             loopCount = loops;
     26             initialRemainingSeconds = remainingSeconds = duration;
     27         }
     28 
     29         public event Action<Type> OnTimerEnd;
     30 
     31         // Handles update that will happen every gametick
     32         public void Tick(float deltaTime)
     33         {
     34             if (remainingSeconds == 0f) return;
     35 
     36             remainingSeconds -= deltaTime;
     37 
     38             CheckForTimerEnd();
     39         }
     40 
     41         private void CheckForTimerEnd()
     42         {
     43             if (remainingSeconds > 0f) return;
     44 
     45             // Will restart timer if the current 'loops' is 1 or greater
     46             remainingSeconds = loopCount-- > 0?initialRemainingSeconds:0f;
     47             
     48             OnTimerEnd?.Invoke(null);
     49         }
     50     }
     51 }