Health Bar Percentages Problem

Hi! I’m having trouble with my health bar percentage and I don’t know why because I divided them and then multiplied them by 100.

Here take a look.
41767-player-health-example.png
(says 50/100 and 0%)

It really doesn’t make since to me because if I set it to 100 then it is fine.

Here is the code:

using UnityEngine.UI;
using System.Collections;

public class PlayerHealth : MonoBehaviour {

	public Image PlayerHealthBar;
	public Text Fraction;
	public Text Percent;
	public int maxHealth = 0;
	public int curHealth = 0;

	// Use this for initialization
	void Start () 
	{
		Fraction.text = curHealth + "/" + maxHealth;
		Percent.text = (curHealth/maxHealth) * 100 + "%";
	}
	
	// Update is called once per frame
	void Update () 
	{

	}
	

}

And here is the setup of it

41768-player-health-settings.png

Well anyways hope someone can help, thanks in advance.

When you do this:

curHealth / maxHealth

, you’re dividing one integer by another integer, and you’re getting an integer returned. In C# (and most other languages), integer division rounds down to the closest integer result. So 7 / 3 = 2. In your case, 50/100 should be .5, but it’s rounded down to 0. For more information, check out the official docs here.

To fix this, you’ll have to force float (decimal) division. The easiest way to do that is to convert one of the values into a float, as float division will be used if either the dividend or the divisor is a float:

Fraction.text = curHealth + "/" + maxHealth;
float curHealthFloat = curHealth;
Percent.text = (curHealthFloat/maxHealth) * 100 + "%";

EDIT:
you should also replace these lines:

public int maxHealth = 0;
public int curHealth = 0;

with this:

public int maxHealth;
public int curHealth

As setting values in the script that you’re overriding in the inspector can have weird effects when you start working with prefabs. The default value for integers are 0 anyways, so setting them to 0 doesn’t really do anything useful. You’re either overriding some value you have set in the inspector, or doing nothing.

Your max and cur health is int, that’s why you get 0, there is no error.
50/100 = 0.5, but only if result is float, you have int result, so it’s 0

Use this:

Percent.text = ((float)curHealth/maxHealth) * 100 + "%"

this will convert curHealth to float, and output will be float