I am displaying my life as float in order to use Time.DeltaTime to regen my health, however when it regenerates the life text is displaying a decimal place
What its showing: Life: 97.02746/100
What I want: Life: 97/100
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class life_system : MonoBehaviour
{
public Image[] hearts;
public Text lifeText;
public float life;
private float lifeIn1Heart;
public int maxLife;//Variable so we can change if we want to
private float lifeRegen = 3f;
void Start()
{
life = 100;
maxLife = 100;
lifeIn1Heart = maxLife / hearts.Length;
}
void Update()
{
//TEMPORARY life control keys
if (Input.GetKeyDown(KeyCode.DownArrow))
{
life -= 5;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
life += 5;
}
if(life < 100)
{
life += lifeRegen * Time.deltaTime;
}
Hearts();
}
public void Hearts()
{
life = Mathf.Clamp(life, 0, maxLife);//Stop life from going less that 0 and from going higher than 100
lifeText.text = ("LIFE: " + life + "/100");
for (int i = 0; i < hearts.Length; i++)
{
bool showHeart = life > i * lifeIn1Heart;
hearts[i].enabled = showHeart;
}
}
}
You can use one more float, add the regen to that float, and check: if the float is higher than one, lesser one from the float, and add one HP to the player. This way, if the player never is supposed to have hp that isn’t a integer, it wont, and the player will never survive if he has 0 hp displayed on the screen.
But, you can also make this :
public void Hearts()
{
lifeText.text = ("LIFE: " + life.Tostring("00.") + "/100"; //return a string showing the closest int to the HP float (1.3 will display 01, 1.6 will display 02)
Debug.Log(Mathf.Ceil(life)); // 1.3 will display 2, 1.6 will display 2
Debug.Log(Mathf.Floor(life));// 1.3 will display 1, 1.6 will display 1
}
For some reason the hearts display more than what it says in the life text, if I put the life to 0 it still displays half a heart… for example if the text says 50/100 the hearts displayed is 5 and a half (which is 55)… for some reason the hearts are half a heart ahead of the text… any idea why?
for (int i = 0; i < hearts.Length; i++)
{
bool showHeart = life > i * lifeIn1Heart;
hearts[i].enabled = showHeart;
}
When i = 0, i*lifeIn1Heart will be equal to 0. This Way, having 0.0001 HP will make half a heart appear. And you have a script regenerating your HP. I guess this is why, but i’m not entirely sure.
I’m not sure if this will solve your issue, but you can try.
for (int i = 0; i < hearts.Length; i++)
{
bool showHeart = life > (i+1) * lifeIn1Heart;
hearts[i].enabled = showHeart;
}
I’m not sure why it does this. You should maybe add on the left a text box showing the true float HP, to see if when regenerating, you actually have truely 100HP, or maybe 99,7386 hp. Maybe the use of something like Mathf.Floor or something like that will help. Or maybe the solution i gave you isn’t good.