- Home /
Recharge delay on shield regen through coroutines
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?
StopAllCoroutines() have done the trick. I was also trying to use new StopCoroutine(Coroutine coroutine) method, but yielded coroutines try to continue, which resides in printing out "Coroutine continue failure" in console. Which is weird.
Glad to have helped. If the comment helped you please convert it to answer and accept it.
Just post your comment as an answer, I will accept it, because I dunno how to convert it.
Answer by CodeElemental · Dec 25, 2014 at 02:18 PM
You can use StopAllCoroutines() to stop all executing coroutines before starting a new one. That way you can ensure that there is only one instance of a specified coroutine at a given time. Take a look at StopAllCoroutines and StopCoroutine
Answer by Wisearn · Dec 25, 2014 at 02:28 PM
maybe a crude fix but you can run a timer like this>
float rechargeCooldown = 0f;
void Update () {
rechargeCooldown = Mathf.Max(rechargeCooldown - Time.deltaTime, 0f);
}
public float ApplyDamage (float damage) {
rechargeCooldown = rechargeDelay;
}
public void RechargeShield () {
if (rechargeCooldown == 0f && currentShield < maxShield) {