0
\$\begingroup\$

I want to show the current health and stamina of the player using GUI.Label. All is working fine however it shows the values with decimals to the millionth (example: http://gfycat.com/SkeletalSinfulKouprey). How would I go about showing only the whole number?

My code:

 var cur_stamina : float; 
    var cur_health : float;

    var staminaRegenRate : float = 5;
    var healthRegenRate : float = 1;

    //regen
    if(cur_stamina < max_stamina){
        cur_stamina += staminaRegenRate * Time.deltaTime;
    }
    if(cur_health < max_health){
        cur_health += healthRegenRate * Time.deltaTime;
    }

    function OnGUI(){
        GUI.Label(Rect(1,1,100,20), "Health: " +cur_health);
        GUI.Label(Rect(1,15,1000,20), "Stamina: " +cur_stamina);
        GUI.Label(Rect(1,30,100,20), "Ammo: " +cur_ammo);
    }
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Convert it to an integer? \$\endgroup\$
    – Ben
    Commented Jul 27, 2014 at 6:39
  • \$\begingroup\$ @Ben then the regen doesn't work \$\endgroup\$
    – eren_tetik
    Commented Jul 27, 2014 at 6:44
  • 5
    \$\begingroup\$ Convert it to an integer just before you send it to GUI.Label. Don't convert the actual variable, create a temporary. \$\endgroup\$
    – Ben
    Commented Jul 27, 2014 at 7:02

2 Answers 2

6
\$\begingroup\$

Don't forget that every object in .NET has a ToString() method. Many of the built-in value types accept an optional formatting argument; numeric types in particular are easy to format with standard formatting or custom formatting.

For example, instead of just passing cur_health, you could pass cur_health.ToString("n0").

For the specific question, you could also truncate using Mathf.FloorToInt.

\$\endgroup\$
0
\$\begingroup\$

You could use a bitwise OR to just truncate:

GUI.Label(Rect(1,1,100,20), "Health: " +cur_health | 0);

Or, if you care about accuracy, you can use Unity's API to round it:

GUI.Label(Rect(1,1,100,20), "Health: " Mathf.Round(+cur_health));
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .