I’m working on a health regen system for a game and I’m running into some issues. Seems no one else has tried this as far as I can tell so I HAVE Googled it already.
Anyway I want the system to act like this:
When damage is received, wait x seconds and and then start the regen process. If damage is received WHILE regening, stop the regen process and start over.
I can’t quite figure out how exactly to do this. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthScript : MonoBehaviour {
int maxHealth = 100; //Player's Max health
public float currentHealth; //Player's Current health
public float regenSpeed; //Regen speed (wait time)
public float regenWaitTime; //Time before regen starts
bool isRegen = false; //If regening
bool canRegen = true; //If can regen
void Start(){
currentHealth = maxHealth; //Sets player health
}
void Update () {
if(currentHealth>maxHealth){
currentHealth = maxHealth;
}else if(currentHealth!=maxHealth && !isRegen){ //If they have health less than max
StartCoroutine(Regen()); //Start regen
}
}
//Function for health regen
IEnumerator Regen(){
isRegen = true; //Set regenning to true
yield return new WaitForSeconds(regenWaitTime); //Wait for delay
while(currentHealth<maxHealth){ //Start the regen cycle
currentHealth += 1; //Increase health by 1
yield return new WaitForSeconds(regenSpeed); //Wait for regen speed
}
isRegen = false; //Set regenning to false
}
//Function for dying
void Die(){
Debug.Log(this.name+" died."); //This is where death cycle will go
canRegen = false;
}
//Function for taking damage
public void TakeDamage(float damage){
if(currentHealth<=0){
Die();
}else{
currentHealth -= damage; //Remove health
}
}
}