Here is a basic script for a health system that I will be using in my game. So far the health decrease & increase is triggered using keypresses, but later on with colliders. I was wondering how I can rewrite the script so that when the player losses health, a time delay must happen before losing more health. This is to prevent quickly draining the player's health.
Health Script:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health: MonoBehaviour {
public int health;
public int numOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
void Update() {
if (health > numOfHearts) {
health = numOfHearts;
}
for (int i = 0; i < hearts.Length; i++) {
if (i < health) {
hearts[i].sprite = fullHeart;
} else {
hearts[i].sprite = emptyHeart;
}
if (i < numOfHearts) {
hearts[i].enabled = true;
} else {
hearts[i].enabled = false;
}
}
if (Input.GetKeyDown(KeyCode.O)) {
TakeDamage(1);
}
if (Input.GetKeyDown(KeyCode.P)) {
GainHealth(1);
}
}
void TakeDamage(int damage) {
health -= damage;
}
void GainHealth(int gain) {
health += gain;
}
}