Search Unity

Cooldown Timer Tutorial (Spawners, Abilities, Combat, etc)

Discussion in 'Scripting' started by xjjon, Jan 21, 2020.

  1. xjjon

    xjjon

    Joined:
    Apr 15, 2016
    Posts:
    613
    Cooldown Timers are a useful part of any game. The simple way to implement them is to keep track of `timeRemaining` and subtract time in `Update()`. It works and is quick but it's not very robust. Also it's hard to share it between components and classes. Generic C# timers work but don't follow the same update schedule as Unity objects.


    I create a pretty simple and easy to use Cooldown Timer script that follows Unity's update pattern.

    Also included a tutorial and sample demo to go with it here. The code is also available on github.

    Basically you can use it by creating a new CooldownTimer and then registering a handler:

    Code (CSharp):
    1.  
    2. void SetupTimer() {
    3.     _cooldownTimer = new CooldownTimer(TimerDuration);
    4.     _cooldownTimer.TimerCompleteEvent += OnTimerComplete;
    5. }
    6.  
    7. void OnTimerComplete() {
    8.    //Do Something
    9. }
    10.  
    The timer is started by calling `Start()`. It can also be configured to be recurring (repeated).

    To create something like an ability or attack cooldown, you can just check if the timer is active:

    Code (CSharp):
    1.  
    2. public void Attack() {
    3.     if (_cooldownTimer.IsActive)
    4.     {
    5.          return;
    6.     }
    7.     _cooldownTimer.Start();
    8.     // Do attack logic
    9. }
    10.  
    I've been using this pattern for many projects now and have found it's nice to be able to have a generic way to keep track of timers and cool downs. It's available here.

    Would love to hear your thoughts on it and any comments / suggestions / questions you may have.

    Cheers
     
    bubbny, battman00 and Kurt-Dekker like this.
  2. stickylab

    stickylab

    Joined:
    Mar 16, 2016
    Posts:
    92
    thanks ,hope i can