I’m trying to implement a recharge delay for my energy shield class using coroutines. The idea is to reset duration of the delay each time damage is received. I’ve got this code so far:
public class ShieldStats : MonoBehaviour {
public float currentShield = 0;
public float maxShield = 100f;
public float rechargeRate = 0f;
public float rechargeDelay = 0f;
public float rechargeDelay = 0f;
private bool shieldRechargeAllowed = true;
void Start () {
InvokeRepeating ("RechargeShield", 1, 0.1f);
}
public float ApplyDamage (float damage) {
StartCoroutine (DisallowShieldRegenForXSeconds (rechargeDelay));
......
}
public void RechargeShield () {
if (shieldRechargeAllowed && currentShield < maxShield) {
currentShield += rechargeRate;
if (currentShield > maxShield)
currentShield = maxShield;
}
}
void OnDisable () {
CancelInvoke ("RechargeShield");
}
IEnumerator DisallowShieldRegenForXSeconds (float rechargeDelay) {
shieldRechargeAllowed = false;
yield return new WaitForSeconds (rechargeDelay);
shieldRechargeAllowed = true;
}
}
Thing is, each time damage applied - new coroutine is instantiated. When the damage is received after old coroutine yield’s it creates new coroutine which sets flag to false, but when old coroutine starts again - it sets bool to true, where it should be false.
Is there a way to stop previous coroutine instances and keep only latest one called? Or should I use deltatime for this purposes?