Home > other >  Heal reset Unity C#
Heal reset Unity C#

Time:08-09

I implemented healing into my Unity project and have a timer for when the player can heal and I want the timer to reset every time the player takes damage but I can't seem to get it to work.. here is my code:

private void HealthRegen()
{
    timer  = Time.deltaTime;
   
    if (timer > timeToHeal) 
    {
        StartCoroutine(HealthRegenCo());
    }
    if (damaged == true)
    {
        timer = 0f;
    }
}

private void SetHealth(float value)
{
    currentHealth = Mathf.Clamp(value, 0f, 100f);
    healthbar.value = currentHealth;
}

private IEnumerator HealthRegenCo()
{
    while (enabled)
    {
       yield return new WaitForSeconds(0.1f);
       SetHealth(currentHealth   healAmount);
       Save();
    }
}

CodePudding user response:

I see what happened here, let me descriptively explain what your code does.

I assume that HealthReign() is called in Update(), and the timer is increasing. When the timer goes above timeToHeal, the coroutine is started. If damage is set to true, timer is set to 0. When the timer goes above timeToHeal, the code inside else if block doesn't get called at all due to it being an else if. Code inside else if is only read when the condition in the if statement is false.

Fix, don't use else if, just use another if

private void HealthRegen()
{
    timer  = Time.deltaTime;
   
    if (timer > timeToHeal) 
    {
        StartCoroutine(HealthRegenCo());
    }
    
    if (damaged == true)
    {
        timer = 0f;
    }
}

CodePudding user response:

Time.deltaTime <-- this is working by Update() , so you can count time by your coroutine. like this.

private void HealthRegen()
{
    StartCoroutine(HealthRegenCo());
}

private void SetHealth(float value)
{
    currentHealth = Mathf.Clamp(value, 0f, 100f);
    healthbar.value = currentHealth;
}

private IEnumerator HealthRegenCo()
{
    while (enabled)
    {
       yield return new WaitForSeconds(0.1f);
       timer  = 0.1f;
       SetHealth(currentHealth   healAmount);
       Save();
       if(timer > timeToHeal)
       {
            yield break;
       }
    }
}

//------------------------ I saw your question yestday , so I think like this is simply , and you can use "HealthOpen" to open or close health.

float time = 0;
public bool HealthOpen = false;

private void Update()
{
    if(HealthOpen)
    {
        time  = Time.detlaTime;
        if(time > 0.1f)
        {
            time = 0;
            setHeal(currentheal   heal);
        }
        if(currentheal >= 100)
        {
            HealthOpen = false;
        }
    }
}    
  • Related