Thursday, March 26, 2015

Cooldown.cs

I built a "Cooldown" class I find myself using constantly in Unity. Maybe you might find it useful. Here's how I might typically use it:



if(state == States.Reloading)
{
    // returns true only if the cooldown duration lapses on this frame
    if(reloadCooldown.Advance()) 
    {
        state = States.Ready;
        hideReloadMeter();
    }
    else
    {
        // this would lerp a progress bar for example
        updateReloadMeter(reloadCooldown.Progress);
    }
}



And here's the class!  Note that "Progress" will always reach 0 on the frame that "Advance" returns true, even if it auto-resets.  This is why it is updated as a variable and isn't just resolved from the fractional duration variables, which are already reset at that point.



using UnityEngine;

public class Cooldown
{
    #region properties
    public float Progress { get { return progress; } }
    #endregion

    #region state
    float duration;
    float maxDuration;
    float progress;
    bool autoReset;
    #endregion

    public Cooldown(float duration)
        : this(duration, true)
    {
    }

    public Cooldown(float duration, bool autoReset)
    {
        maxDuration = duration;

        this.autoReset = autoReset;

        Reset();

        updateProgress();
    }

    public void Reset()
    {
        duration = maxDuration;
    }

    public bool Advance()
    {
        return Advance(Time.deltaTime);
    }

    public bool Advance(float seconds)
    {
        duration = Mathf.Max(0, duration - seconds);

        updateProgress();

        if(duration == 0)
        {
            Reset();
            return true;
        }
        return false;
    }

    public void updateProgress()
    {
        progress = 1 - duration / maxDuration;
    }
}

No comments:

Post a Comment