How do I make my healthbar change color depending on damage?
Hello, I'm really stuck on my healthbar and could really use some help! I'm trying to make my healthbar go from green -> yellow -> red depending on how much damage the player has gotten. But my current attempt at a color change code in my setHealth() {...} just makes the healthbar vanish :/
Any ideas on what I can do to make this work? Because I'm really lost :( THANKS!
PS. I've commented out the color code part on purpose!
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;
setHealth();
}
void TakeDamage(float amt) {
currentHitPoints -= amt;
if (currentHitPoints <=0) {
currentHitPoints = 0;
Die();
}
setHealth();
}
void Die() {
if(gameObject.tag == "Enemy") {
Instantiate(destroyFX, this.transform.position, this.transform.rotation);
Destroy (gameObject);
}
}
public void setHealth() {
float enemyHealthCalc = currentHitPoints / hitPoints;
healthbar.transform.localScale = new Vector3(enemyHealthCalc, healthbar.transform.localScale.y, healthbar.transform.localScale.z);
/*
if (enemyHealthCalc < 0.1f) {
healthbar.color = Color.Lerp(endColor, middleColor, enemyHealthCalc * 2);
}
else {
healthbar.color = Color.Lerp(middleColor, startColor, (enemyHealthCalc - 0.5f) * 2);
}
*/
}
}
you are almost right.
Color Lerp(Color a, Color b, float t);
using Color.Lerp need notice that "t" is clamped between 0 and 1
How would one clamped "t" between 0 and 1? $$anonymous$$athf.clamp or something?
Answer by say_forever · Nov 18, 2015 at 09:31 AM
you can write in Update() like
private float t = 0;
void Update()
{
Color c = Color.Lerp(Color.white, Color.black, t);
t = t + 0.01f;
}
Your answer
Follow this Question
Related Questions
Kill Count and Health Bar Scripts 0 Answers
My health bars image.fillAmount doesnt change. 4 Answers
Bullet Damage Player's Healthbar,Bullet Damage Other Player's Health 2 Answers
Unity Multiplayer: when i hit another player all players health bars go down 0 Answers
Hey Guys I want my player to lose one Heartcontainer if he collides with the enemy 0 Answers