- Home /
Question by
SPOTNINJADUD7890 · Aug 16, 2016 at 05:02 AM ·
c#unityeditorimage
My health bar is not filling to the health variable please help!
//start
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EnemyHealth : MonoBehaviour {
public int maxHealth = 500;
public int curHealth = 500;
public Image Healthbar;
//initialization
void Start ()
{
Healthbar = transform.FindChild ("EnemyCanvas").FindChild ("HealthBG").FindChild ("Health").GetComponent<Image> ();
}
// Update
void Update () {
if (curHealth <1){
Destroy(gameObject);
Healthbar.fillAmount = (float)curHealth / (float)maxHealth;
}
}
void OnCollisionEnter(Collision col) {
if (col.gameObject.tag == "BubbleBullet"){
curHealth -= 20;
Destroy(col.other);
}
}
}
Please help me!
Comment
Have you tried using Sliders? It's a built in GUI thing that's perfect for healthbars.
Best Answer
Answer by saschandroid · Aug 16, 2016 at 05:48 AM
if (curHealth <1){
Destroy(gameObject);
Healthbar.fillAmount = (float)curHealth / (float)maxHealth;
}
The fill amount is only calculated (updated) if the current health is below 1. You probably want to move the calculation outside the if statement (?).
Your answer
![](https://koobas.hobune.stream/wayback/20220612090910im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Navigate UI with gamepad 0 Answers
Adding a component in editor mode by selecting an Enum. 1 Answer