0
votes

My Enemy script activates a raycast and line renderer when within range of the player. However using the Health script below my health slider continues to decrease in value after my enemy is destroyed or I move the player out of range.

New to unity, hope this is not too simple. I guess its cause there is nothing after CurrentHealth -= Time.deltaTime * 10; to stop the health decreasing but how would I fix this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Health : MonoBehaviour
{
    public Text HealthText;
    public Slider HealthSlider;

    public float MaxHealth = 100;
    static public float CurrentHealth = 100;

    public LineRenderer lineRenderer;

    private void Update()
    {
        HealthUI();

        if (CurrentHealth > 0)
        {
            if (lineRenderer.enabled) 
            {
                CurrentHealth -= Time.deltaTime * 10;   
            }
        }
    }   

    public void HealthUI()
    {
        HealthSlider.value = CurrentHealth / MaxHealth;
        HealthText.text = "HEALTH " + ((int)(CurrentHealth / MaxHealth * 100)).ToString() + "%";
    }  
}

Thanks!

1
Is there a special reason it is static? if(CurrentHealth > 0) should prevent it from decreasing .. maybe it will not exactly terminate at 0 but a bit below but than it should stop .. at least from the code you provide ... Are you sure nothing else is changing the value? Especially since it is static it might be easily changed by another component - derHugo
You could try Mathf.Clamp to ensure that the value always stays within a certain range. docs.unity3d.com/ScriptReference/Mathf.Clamp.html - Reasurria
Where do you disable the LineRenderer? It is always enabled - Neil Knight

1 Answers

0
votes

Unless CurrentHealth is modified from another script the only reason why the health is decreasing is because the line renderer referenced is not disabled. So make sure that you reference the correct line renderer and that it is disabled when no enemy is nearby.

Notice that your current approach requires you to have only one line renderer that is toggled on and off depending if an enemy is in sight. This can get messy. I think a better approach would be to call a TakeDamage method directly on the health script when the player is in sight:

using UnityEngine;
using UnityEngine.UI;

public class Health : MonoBehaviour
{
    public Text HealthText;
    public Slider HealthSlider;

    public float MaxHealth = 100;
    public float CurrentHealth = 100;

    public void TakeDamage()
    {
        if (CurrentHealth > 0)
        {
            CurrentHealth -= Time.deltaTime * 10;
        }
    }

    private void Update()
    {
        HealthUI();
    }

    public void HealthUI()
    {
        HealthSlider.value = CurrentHealth / MaxHealth;
        HealthText.text = "HEALTH " + ((int)(CurrentHealth / MaxHealth * 100)).ToString() + "%";
    }
}