- Home /
C# Health regeneration delay after hit
I want to make it so if the player is hit, 5 seconds after the player is hit they start regenerating health. If while the timer is going up the player gets hit again it resets the timer back to 0. It is only setting one enemy of object type EnemyController to the enemy. If I have two enemies for example it will reset the timer if one of the enemies hit me but not if the other one does. I tried using the mesh collider to have the enemies damage the player when their hands collided with the player but I couldn't get it to work (Vector3.Distance(transform.position, enemy.transform.position) <= 5) this is the condition I used to deal the damage. I want to be able to keep track of all of the enemies' positions. That way no matter which one does damage, the timer will reset. I used this script for the player health
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealthManager : MonoBehaviour
{
public float startingHealth = 100;
public float currentHealth;
public float healAmountPerSec = 10;
public float regenStartCooldown;
public float timeStamp = 0;
public EnemyController enemy;
bool attack;
// Start is called before the first frame update
void Start()
{
//set current health to starting health, set regencooldown, set enemy
currentHealth = startingHealth;
regenStartCooldown = 5;
enemy = FindObjectOfType<EnemyController>();
}
// Update is called once per frame
void Update()
{
attack = enemy.attack;
/*if health<0 , dead; if health less than start, timer starts; if health > 0,
*timer ends; if enemy attacks again, timer set back to 0
*/
if (currentHealth <= 0)
{
gameObject.SetActive(false);
}
if (currentHealth < startingHealth)
{
timeStamp += Time.deltaTime;
//start regen once cooldown timer reached
if(timeStamp >= regenStartCooldown)
{
currentHealth += healAmountPerSec * Time.deltaTime;
}
}
if (currentHealth >= startingHealth)
{
currentHealth = 100;
timeStamp = 0;
}
if (Vector3.Distance(transform.position, enemy.transform.position) <= 5 && attack)
{
timeStamp = 0;
}
}
//subtract current health by damage amount
public void HurtPlayer(int damageAmount)
{
currentHealth -= damageAmount;
}
}
The problem I'm having is lines 20 and 50-53
void Start()
{
enemy = FindObjectOfType<EnemyController>();
}
void Update()
{
if (Vector3.Distance(transform.position, enemy.transform.position) <= 5 && attack)
{
timeStamp = 0;
}
}
Your answer
Follow this Question
Related Questions
[C#]Health Regeneration and Delay 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Instantiate on value change 2 Answers
adding a delay to shooting 2 Answers