# 2. Resources Cooldowns and Charges
Part of [[Ability System]]. Previous: [[1. Ability Design and the Level Up! Lens]]. Next: [[3. Status Effects Stacking and Tags]].
> [!warning] Test status
> Type-checked against 6000.5.8f1. Both classes passed their tests on .NET 10 (part 7).
## 2.1 ResourcePool
```csharp
// Assets/Scripts/Abilities/Core/ResourcePool.cs
using System;
/// <summary>
/// A spendable resource (mana, stamina, energy, rage) with regeneration and an optional
/// regen delay after spending. Time is passed in explicitly so it is deterministic and testable.
/// </summary>
public sealed class ResourcePool
{
public ResourcePool(string id, float max, float regenPerSecond, float regenDelayAfterSpend = 0f, float start = -1f)
{
if (max <= 0f)
throw new ArgumentOutOfRangeException(nameof(max));
Id = id;
Max = max;
RegenPerSecond = regenPerSecond;
RegenDelayAfterSpend = regenDelayAfterSpend;
Current = start < 0f ? max : Math.Min(start, max);
}
public string Id { get; }
public float Max { get; private set; }
public float Current { get; private set; }
public float RegenPerSecond { get; set; }
public float RegenDelayAfterSpend { get; set; }
public float Normalized => Current / Max;
/// <summary>Raised with (current, max) whenever Current changes.</summary>
public event Action<float, float> Changed;
float _regenBlockedFor;
public bool CanAfford(float cost) => cost <= 0f || Current >= cost;
public bool TrySpend(float cost)
{
if (cost <= 0f)
return true;
if (Current < cost)
return false;
Current -= cost;
_regenBlockedFor = RegenDelayAfterSpend;
Changed?.Invoke(Current, Max);
return true;
}
public void Restore(float amount)
{
if (amount <= 0f)
return;
var before = Current;
Current = Math.Min(Max, Current + amount);
if (Current != before)
Changed?.Invoke(Current, Max);
}
public void SetMax(float max, bool keepRatio)
{
if (max <= 0f)
throw new ArgumentOutOfRangeException(nameof(max));
var ratio = Normalized;
Max = max;
Current = keepRatio ? ratio * max : Math.Min(Current, max);
Changed?.Invoke(Current, Max);
}
public void Tick(float dt)
{
if (dt <= 0f)
return;
if (_regenBlockedFor > 0f)
{
var used = Math.Min(_regenBlockedFor, dt);
_regenBlockedFor -= used;
dt -= used;
if (dt <= 0f)
return;
}
if (RegenPerSecond > 0f && Current < Max)
Restore(RegenPerSecond * dt);
}
}
```
What to notice:
- **`TrySpend` is all-or-nothing.** It never leaves the pool half-spent. Callers check `CanAfford` for UI ("grey out the icon") and call `TrySpend` to commit.
- **The regen delay** (`RegenDelayAfterSpend`) is the classic "stamina waits a second after you sprint" feel. `Tick` uses up the delay first and regenerates only with the time that's left, so a long frame doesn't skip the delay.
- **`SetMax(max, keepRatio)`:** when a level-up raises max mana, keep the ratio (50% stays 50%). When a debuff lowers it, clamp. The caller decides which.
- **`Changed` fires only on real changes**, so a UI bar subscribed to it does no work while full.
## 2.2 CooldownTracker
```csharp
// Assets/Scripts/Abilities/Core/CooldownTracker.cs
using System;
using System.Collections.Generic;
/// <summary>
/// Per-ability cooldowns with charges, plus one shared global cooldown (GCD).
/// Uses absolute timestamps (seconds, double) so nothing needs ticking.
/// A 1-charge ability is a classic cooldown; N charges recharge one at a time.
/// </summary>
public sealed class CooldownTracker
{
sealed class Entry
{
public int MaxCharges;
public double RechargeSeconds;
public int Charges;
public double NextChargeAt; // valid when Charges < MaxCharges
}
readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry>();
double _gcdReadyAt;
public void Register(string abilityId, double cooldownSeconds, int maxCharges = 1)
{
if (maxCharges < 1)
throw new ArgumentOutOfRangeException(nameof(maxCharges));
_entries[abilityId] = new Entry { MaxCharges = maxCharges, RechargeSeconds = Math.Max(0, cooldownSeconds), Charges = maxCharges };
}
public bool IsRegistered(string abilityId) => _entries.ContainsKey(abilityId);
public int Charges(string abilityId, double now)
{
var e = Get(abilityId);
Refill(e, now);
return e.Charges;
}
public bool IsReady(string abilityId, double now) => Charges(abilityId, now) > 0;
public bool GlobalReady(double now) => now >= _gcdReadyAt;
public double GlobalRemaining(double now) => Math.Max(0, _gcdReadyAt - now);
/// <summary>Seconds until the next charge (0 when full).</summary>
public double Remaining(string abilityId, double now)
{
var e = Get(abilityId);
Refill(e, now);
return e.Charges >= e.MaxCharges ? 0 : Math.Max(0, e.NextChargeAt - now);
}
/// <summary>0..1 progress of the charge currently recharging (1 when full). Handy for radial UI.</summary>
public float RechargeProgress(string abilityId, double now)
{
var e = Get(abilityId);
Refill(e, now);
if (e.Charges >= e.MaxCharges || e.RechargeSeconds <= 0)
return 1f;
return (float)(1.0 - (e.NextChargeAt - now) / e.RechargeSeconds);
}
/// <summary>Consumes one charge. Returns false if none are available.</summary>
public bool TryConsume(string abilityId, double now, double globalCooldown)
{
var e = Get(abilityId);
Refill(e, now);
if (e.Charges <= 0)
return false;
if (e.Charges == e.MaxCharges)
e.NextChargeAt = now + e.RechargeSeconds; // recharge starts when you drop below full
e.Charges--;
if (globalCooldown > 0)
_gcdReadyAt = Math.Max(_gcdReadyAt, now + globalCooldown);
return true;
}
/// <summary>Cooldown reduction effects: shift the pending recharge earlier by seconds.</summary>
public void Reduce(string abilityId, double now, double seconds)
{
var e = Get(abilityId);
Refill(e, now);
if (e.Charges >= e.MaxCharges || seconds <= 0)
return;
e.NextChargeAt -= seconds;
Refill(e, now);
}
public void ResetAll(double now)
{
foreach (var e in _entries.Values)
e.Charges = e.MaxCharges;
_gcdReadyAt = now;
}
static void Refill(Entry e, double now)
{
while (e.Charges < e.MaxCharges && now >= e.NextChargeAt)
{
e.Charges++;
if (e.Charges < e.MaxCharges)
e.NextChargeAt += e.RechargeSeconds; // chain from when the last charge finished, not from now
}
}
Entry Get(string abilityId)
{
if (!_entries.TryGetValue(abilityId, out var e))
throw new KeyNotFoundException("Ability not registered: " + abilityId);
return e;
}
}
```
### Timestamps, not timers
The tracker stores *when* a charge comes back (`NextChargeAt`), not *how long is left*. That has three benefits:
1. **Nothing to tick.** Forty abilities on fifty enemies cost nothing per frame. They're computed when someone asks.
2. **Pause works for free** if the caller passes a clock that stops (the Unity layer uses `Time.timeAsDouble`, which stops at `timeScale = 0`).
3. **Save and load** is just storing the timestamps relative to "now".
### Charges
- A 1-charge ability is an ordinary cooldown.
- With N charges, the recharge starts when you drop **below full**. When one charge finishes, the next one starts **from that moment** (`NextChargeAt += RechargeSeconds`), not from when you next look. Without that chaining, a player who checks the UI late would lose recharge time. A test pins this down: two dashes at t = 0 come back at t = 4 and t = 8.
- `RechargeProgress` gives 0…1 for the charge that's currently recharging. That's exactly what a radial cooldown mask needs (part 6).
### GCD and cooldown reduction
- `TryConsume(id, now, globalCooldown)` sets the shared GCD. Abilities with `triggersGlobalCooldown = false` (blink, potions) pass 0 and can be used during it.
- `Reduce(id, now, seconds)` moves the pending charge earlier. That covers "hitting an enemy reduces Dash's cooldown by 1 s" and "−20% cooldown" talents (apply the percentage when you build the spec in part 5, not here).
## 2.3 Try it in isolation
These classes don't need a scene. In an EditMode test (part 7), or in a throwaway `MonoBehaviour`:
```csharp
// Assets/Scripts/Abilities/Samples/CooldownScratch.cs
using UnityEngine;
public sealed class CooldownScratch : MonoBehaviour
{
readonly CooldownTracker _cd = new CooldownTracker();
void Start() => _cd.Register("dash", 4, 2);
void Update()
{
var now = Time.timeAsDouble;
if (UnityEngine.InputSystem.Keyboard.current != null && UnityEngine.InputSystem.Keyboard.current.spaceKey.wasPressedThisFrame)
Debug.Log(_cd.TryConsume("dash", now, 0) ? "Dash!" : "No charges");
if (Time.frameCount % 30 == 0)
Debug.Log(
quot;dash charges {_cd.Charges("dash", now)}, next in {_cd.Remaining("dash", now):0.0}s");
}
}
```