- Home /
How can i make a Healthbar the same width no matter the health?
I'm trying to have a Healthbar(Canvas) above every enemies head, and display their health. What I want is the exact same width for every bar, no matter how much health the enemy has. If they have low health, the bar goes down fast, if they have high health the bar goes down slowly. Here's my script:
public class EnemyHealth : MonoBehaviour
{
public float MaxHealth;
[Space]
public RectTransform HealthBar;
private float CurrentHealth;
void Start () {
CurrentHealth = MaxHealth;
HealthBar.sizeDelta = new Vector2(CurrentHealth, HealthBar.sizeDelta.y);
}
void Update () {
//this is for other stuff
}
}
Answer by Retropaint · May 10, 2019 at 08:02 PM
I'm sorry to waste your time, but I have been trying to understand what the problem was for a while but I still cannot get it. Why would you want the health bar to be same the width if this is REPRESENTING the health? Shouldn't it go down WITH the health? I can only assume that you have a high amount of health, like 100, and this causes your UI object to be massively big. If this is the case, then this is probably what you are looking for:
Using UnityEngine.UI;
//Assign a new empty UI object to the bar. Make its size 1,1,1. This is the pseudo script of the parent object.
//By doing this, the size of the actual bar would be 1 of the empty object.
public float Health = 5;
public float MaxHealth = 10;
void ChangeBarSize()
{
RectTransform.sizeDelta = Health / MaxHealth, RectTransform.sizeDelta.y;
}
//The result will be 0.5, half of 1. This causes the parent to have its x be 0.5 which will in turn cause the actual bar to be its halved size.
//If it were 0.25, the size of the actual bar will be the quarter of its own size.
//This means that if you only change the parent's x size (max must be 1), then you will always get the same size for the actual bar.
I hope this is what you are looking for. You can also use the 'Filled image' method which is actually a preferred way. It seems like you wanted to go for a more 'raw' approach, changing the size of the image directly rather than using the 'Filled Image' method, so I just followed. I strongly suggest you use the mentioned method, though. There are tons of videos of it, so I wont bother giving links.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
health bar goes down with time 1 Answer
identifier expected 1 Answer