healthbar color.lerp issue

I’m trying to make my healthbar turn color the more damage it gets (green → yellow → red), but for some reason the healthbar vanishes when my enemies are being hit :confused: The code works fine, beside the coloring stuff in void TakeDamage(float amt). If I comment out the coloring part of the code, then my healthbar works without issues.

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

public class EnemyHealth : MonoBehaviour {
	
	public float hitPoints = 100f;
	public float currentHitPoints;
	public GameObject destroyFX;
    public Image healthbar;

    public Color32 startColor;
    public Color32 middleColor;
    public Color32 endColor;

    void Start () {
		currentHitPoints = hitPoints;
	}
	
	void TakeDamage(float amt) {
		currentHitPoints -= amt;

        
        float healthCalc = currentHitPoints / hitPoints; 
        setHealthbar(healthCalc);

        if (healthCalc < 0.1f) {
            healthbar.color = Color.Lerp(endColor, middleColor, healthCalc * 2);
        }
        else {
            healthbar.color = Color.Lerp(middleColor, startColor, (healthCalc - 0.5f) * 2);
        }

        if (currentHitPoints <=0) {
			currentHitPoints = 0;
			Die();
		}
	}
	
	void Die() {
		if(gameObject.tag == "Enemy") {
			Instantiate(destroyFX, this.transform.position, this.transform.rotation); 
			Destroy (gameObject);
		}
	}

    public void setHealthbar (float enemyHealth) {
        healthbar.transform.localScale = new Vector3(enemyHealth, healthbar.transform.localScale.y, healthbar.transform.localScale.z);
    }

}

The only problem I see is in

healthbar.color = Color.Lerp(middleColor, startColor, (healthCalc - 0.5f) * 2);

If healthCalc is less than 0.5 than the result will be negative and won’t give you the desired results. Instead do

healthbar.color = Color.Lerp(middleColor, startColor, Mathf.Clamp01(healthCalc - 0.5f) * 2);

That way the result will either be zero or positive. Hope that fixes your issue.