- Home /
Health Bar doesnt fit my float var
im still beginner in Unity..
so i have this script to set my Health Bar but it doesnt fit with float var. what logic should i use to this? ( i know i should change " healthBar.SetMaxHealth(); " logic but i dont know what code to use for it. Any suggestion?
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float startHealth = 50f;
private float health;
[Header("Unity Stuff")]
public HealthBarScript healthBar;
private void Start()
{
health = startHealth;
healthBar.SetMaxHealth(startHealth);
}
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
healthBar.SetHealth(health);
}
void Die()
{
Destroy(gameObject);
}
}
Answer by ShadyProductions · May 11, 2020 at 09:22 AM
When I implement a health bar, I use a slider component which has a build in slide between a min and max value. You can set these in the inspector like 0 min value and 100 max value for example.
There are a lot of tutorials on this on youtube.
https://www.youtube.com/watch?v=BLfNP4Sc_iA&t=300s
Incase you want to normalize a value to be between 0-1 you can scale the value.
To scale, you need to divide your raw value by the total range, and account for an offset if min != 0. For a range of (min, max):
scaledValue = (rawValue - min) / (max - min);
For the common case where min == 0:
scaledValue = rawValue / max;
yes i already watch Brackeys tutorial and use his health bar script. But the thing is, he use his health,maxHealth,etc in integer . In my case, my health stats script is in float and i cant use "healthBar.Set$$anonymous$$axHealth(currentHealth)" logic bcs my data type is float. I need to substitute "healthBar.Set$$anonymous$$axHealth(currentHealth)" code with code that compatible with float
I have already given you the answer to that aswel, normalize your float value between 0-1.
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : $$anonymous$$onoBehaviour
{
public Slider slider;
public Gradient gradient;
public Image fill;
private void Start()
{
slider.maxValue = 1;
slider.value = 1;
}
public float $$anonymous$$axHealth;
public void SetHealth(float health)
{
slider.value = health / $$anonymous$$axHealth;
}
}
Just set the healthbar.$$anonymous$$axHealth = startHealth;
Amazing ! thankyou so much for helping me, it worked ! appreciate it !
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Editing a variable from another script on collision 3 Answers
How do I expose a health serialize script on a health bar ? 0 Answers