- Home /
The question is answered, right answer was accepted
How can i make my health regenerate?
hello guys . i made this health script and i can't seem to regan health every 5 seconds. here is the script :
enter code here var MaxHealth : int = 200;
var CurrentHealth : int;
var GUIhealth: GUIText;
var tex4 : Texture ;
var healthRegan : float = 10.0;
function Start () {
CurrentHealth = MaxHealth;
}
function Update ( ) {
if ( CurrentHealth <= 0 ){
CharacterDeath ();
CurrentHealth += healthRegan * Time.deltaTime * 5; // <== here the part
healthRegan = MaxHealth ;
}
}
function CharacterDeath () {
Application.LoadLevel(Application.loadedLevel);
}
function OnGUI (){
GUIhealth.text = "Health"+ CurrentHealth.ToString();
if (CurrentHealth <= 80)
{
GUI.DrawTexture(Rect(0,0, Screen.width, Screen.height), tex4);
}
}
if my method sucks it will be nice if someone could rearanged =)
Answer by robertbu · Jan 10, 2014 at 09:33 PM
Your current health is not regenerating because 'CurrentHealth' is an integer. Any fractional amount you add to an integer is truncated. A fix is to make 'CurrentHealth' a float. The you will need to either round or floor the value before outputting the value.
Note that GUIText is not part of the GUI system, and therefore you don't need to set 'GUIhealth.text' inside of OnGUI(). In fact since OnGUI() gets called multiple times per frame, you are setting GUIhealth.text multiple times per frame. Move the setting to Update().
GUIhealth.text = "Health"+ Mathf.RoundToInt(CurrentHealth).ToString();