- Home /
So I am trying to make my character regenerate health but reset the time it takes to regen when they are hit. I'm lost and have been at it for hours thanks in advance
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Player_Health : MonoBehaviour { private float start_Health; private float current_health; public Image HealthBar; private float regen; private float regenerate = 10f;
// Use this for initialization
void Start () {
start_Health = 100;
current_health = start_Health;
}
public void OnTriggerEnter(Collider col)
{
if (col.tag == "Enemy")
{
current_health -= 10;
Debug.Log(current_health);
HealthBar.fillAmount = current_health / start_Health;
}
}
public void regenerating()
{
if ((Time.time > regenerate) && (current_health < start_Health))
{
current_health += 10;
Debug.Log(current_health);
HealthBar.fillAmount = current_health / start_Health;
}
}
// Update is called once per frame
void Update ()
{
regenerating();
}
}
Answer by $$anonymous$$ · Sep 12, 2017 at 03:38 AM
You probably want to do something like this, you need to keep track of when your countdown was last triggered
using UnityEngine;
using UnityEngine.UI;
public class Player_Health: MonoBehaviour
{
private float start_Health;
private float current_health;
public Image HealthBar;
private float regen;
private float regenerate = 10f;
private float lastTime; //This will keep track of when you last regenerated
// Use this for initialization
void Start()
{
start_Health = 100;
current_health = start_Health;
lastTime = Time.time;
}
public void OnTriggerEnter(Collider col)
{
if (col.tag == "Enemy")
{
current_health -= 10;
Debug.Log(current_health);
HealthBar.fillAmount = current_health / start_Health;
lastTime = Time.time;//this will reset your delay
}
}
public void regenerating()
{
if ((Time.time > lastTime + regenerate) && (current_health < start_Health))//this will trigger when the time is greater than lastTime plus your delay
{
current_health += 10;
Debug.Log(current_health);
HealthBar.fillAmount = current_health / start_Health;
lastTime = Time.time;//this will reset your delay
}
}
// Update is called once per frame
void Update()
{
regenerating();
}
}
Thank you so much! It works I will accept this as completed. I kept on looking through the forums but nothing seemed to work with my current script. Hope you have a great day and I will learn from what you have shown me!
Your answer
![](https://koobas.hobune.stream/wayback/20220612134653im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Health regen script wont work properly 2 Answers
Turn off function 2 Answers
How do i set health to regenerate over a specified range of time? 1 Answer
Regenerate health over time 2 Answers
Sidescroller health bar collision script with regen? 1 Answer