Increase health smoothly not instantly?

I have a soda drinking script where if i press U it allows me to only once add 8 to my current health (60%). It works good but when i press U it instantly goes to 68. How can i make it smooth like it counts up 60 61 62 63 64…68???

Here’s the script:

var isReady : boolean = true;
var isPlayed : boolean;
var healthGiven : boolean;
var sodaDrinkAudio : AudioClip;
var playerMovementScript : PlayerMovementScript;
var health : AdvancedHealth;
var sodaHealth : int = 9;




function Update () {

	if(Input.GetKeyDown("u") && isReady && !healthGiven && !isPlayed && playerMovementScript.currentGun == gameObject)
	{
	healthGiven = true;
	isPlayed = true;
	
	
	if(healthGiven && isPlayed)
	{
	isReady = false;
	giveHealthSoda();
	audio.PlayOneShot(sodaDrinkAudio);
	
	
	}
}
}
	
	

	

	
function giveHealthSoda () {
	
	health.maxHealth += sodaHealth;
	
	
	
	
	

}

Do you want it to slowly increase while you hold U, or slowly increase after you click U once?

–

slowly after i press it once

–

2 Answers

2

Use Mathf.Lerp

Like so:

health.maxHealth += Mathf.Lerp(0, sodaHealth, Time.time);

Should work

didn't work :( but i did this to fix it actually function giveHealthSoda () { yield WaitForSeconds(5); health.maxHealth += 1; yield WaitForSeconds(.08); health.maxHealth += 1; yield WaitForSeconds(.08); health.maxHealth += 1; yield WaitForSeconds(.08); health.maxHealth += 1; yield WaitForSeconds(.08); health.maxHealth += 1; yield WaitForSeconds(.08); health.maxHealth += 1; yield WaitForSeconds(.08); health.maxHealth += 1; yield WaitForSeconds(.0); health.maxHealth += 1;

–

for (var i = 0; i < sodaHealth; i++){
health.maxHealth++;
yield WaitForSeconds(0.8f);
}

Is a much better way to do it than what you did. Look at how much less code. I mean i would probably spend time and think of a better way. But my code is a lot tidier.

your code adds 1 and doesn't stop adding it

–

what you mean it does not stop adding it? There is no logical reason for it carry on past sodaHealth (which is 9) so it will do it 9 times (0-8) then exit the for loop.

–

If this code is put in the Update(), the yield wouldn't work. It has to be put in a function.

–