# Rounding to the nearest int as a Result of a Function?

Hello, I a have a problem with a small Health Regeneration. The part that I’m having problems with works on the following variables:

``````//This will be set and equal to InitialHealth (but modified)
var health : float;

//Amount of Health added to Regenarte (determines the regeneration speed)
var regenSpeed : float = 0.5;
//Time till Regeneration
var TimeToRegenerate : int = 10;
//The timer to get the whole thing to restart
private var regenTimer : float = 0.0;
``````

And this is the function for the regeneration:
function Regenerate ()

``````function Regenerate ()
{
//And the player has lost some Health
if(health < InitialHealth)
{
//If the timer is bigger then the Time to Regenerate,
if(regenTimer < TimeToRegenerate)
{
//Start counting up to surpass the Time to Regernate
regenTimer += Time.deltaTime;
}
else
{
//Regenerate
health += regenSpeed;
}
}
else
{
//Reset the Timer so you can Regenerate next time the
//Player looses Health
regenTimer = 0.0;
}
}
``````

This will give me a Decimal, but is it possible to round the result of health after this function takes place/while it takes place so that the health float is always equal to the nearest int?

Edit :

Here is a little demo script to show what each command does. Create a new scene, create an empty gameObject and attach the below script.

Hit Play.

Now in the Inspector, change the value of myFloat. Watch the output in each GUI Box.

• Mathf.FloorToInt : Returns the largest integer smaller to or equal to float.
• Mathf.CeilToInt : Returns the smallest integer greater to or equal to float.
• Mathf.RoundToInt : Returns float rounded to the nearest integer.

All of the work is done in Update, I added the GUI to give a visual display instead of debug logging an output. So this is how to use one of the commands :

``````myFloatFloor = Mathf.FloorToInt( myFloat );
``````

now the demo script :

``````#pragma strict

var myFloat : float = 0.0;

private var myFloatFloor : float = 0.0;
private var myFloatCeiling : float = 0.0;
private var myFloatRound : float = 0.0;

function Update()
{
// Floor to Int
myFloatFloor = Mathf.FloorToInt( myFloat );

// Ceiling to Int
myFloatCeiling = Mathf.CeilToInt( myFloat );

// Round to Int
myFloatRound = Mathf.RoundToInt( myFloat );
}

function OnGUI()
{
// Floor to Int
GUI.Box( Rect( 10, 10, 100, 30 ), "Floor to Int" );
GUI.Box( Rect( 10, 45, 100, 30 ), "" + myFloatFloor.ToString() );

// Ceiling to Int
GUI.Box( Rect( ( Screen.width * 0.5 ) - 50, 10, 100, 30 ), "Ceiling to Int" );
GUI.Box( Rect( ( Screen.width * 0.5 ) - 50, 45, 100, 30 ), "" + myFloatCeiling.ToString() );

// Round to Int
GUI.Box( Rect( Screen.width - 110, 10, 100, 30 ), "Round to Int" );
GUI.Box( Rect( Screen.width - 110, 45, 100, 30 ), "" + myFloatRound.ToString() );
}
``````