- Home /
Make healthbar size from percentage instead of value.
Hello!
I got this code which determines the size of the health bars in my game.
float currentHealth;
float maxHealth;
void OnChangeHealth (float Health)
{
healthBar.sizeDelta = new Vector2(Health, healthBar.sizeDelta.y);
}
When my units get lots of hp the bar becomes ridiculously long. Can someone please tell me how to make the health bar size depend on percentage of remaining health instead?
Thanks in advance!
//Glimma
Answer by Pigenator · Jun 27, 2017 at 03:58 PM
float currentHealth;
float maxHealth;
float maxSize;
void Start(){
maxSize = transform.localScale.x
}
void OnChangeHealth (float health)
{
healthBar.sizeDelta = new Vector2(health / maxHealth * maxSize,
healthBar.sizeDelta.y);
}
Basically just make another variable for the standard size of the healthbar when the health is full :)
Thank you!
I got it to work with a few modifications.
I got 1 weird problem. If i do this. The health bar is empty. Debug.log do say maxsize value is 100.
Start (){
maxSize = 100;
Debug.Log (maxSize);
}
void OnChangeHealth (float Health)
{
healthBar.sizeDelta = new Vector2((Health / maxHealth * maxSize), healthBar.sizeDelta.y);
}
When i do this it works perfectly. I cant figure out why it wont work with a variable ins$$anonymous$$d of a number.
void OnChangeHealth (float Health)
{
healthBar.sizeDelta = new Vector2((Health / maxHealth * 100),
healthBar.sizeDelta.y); }
Answer by SnStarr · Jun 27, 2017 at 05:56 PM
If using an Image element then...HealthBarImage.fillAmount = currentHealth / maxHealth works the best.
Your answer
Follow this Question
Related Questions
Making a world-space UI look at all split-screen cameras? (split screen health bars) 0 Answers
How to connect multiple sliders for health bar? 3 Answers
How do I have my players stats on the HUD? 0 Answers
Changing the size of the RectTransform's rect 0 Answers
How to I make ui in world space look at the player? 2 Answers