- Home /
How do I regenerate some health each second?
So I know this has been asked before and I've tried a lot of online solutions already. I've written this about 10 times 10 different ways and I simply can't stand that I'm still getting errors. I may not be using Time.deltaTime right since I've never used it for anything before. Code is below, any help is appreciated.
Answer by Josh707 · Jan 15, 2014 at 12:11 AM
You can't do operations like on lines 11 & 12 when they're outside of any functions, so you will have to put them somewhere else like Update if you want it to calculate every frame.
Multiplying second by deltaTime will cause it to constantly decrease until it's 0, at least if you're running faster than 1FPS. It's the time in seconds the last frame took took to complete everything - so it will be a pretty small decimal at high frame rates. In your case I would increment the variable by deltaTime and if it is higher than your limit variable reset it to 0 and do your regeneration stuff.
var regeneration : float = 5.0;
var regenerationRate : float; //time in seconds
private var second : float = 0.0;
function Heal(){
if(curHealth < maxHealth){
second += Time.deltaTime;
if(second >= regenerationRate){
curHealth = Mathf.Min(curHealth + regeneration, maxHealth);
second = 0;
}
}
}
If you want it to be each second then setting the rate to 1.0 should be pretty close to a second, but if you want it to constantly increase then you can just directly increase the health with a value multiplied by deltaTime so it raises consistently.
curHealth = Mathf.Min(curHealth + (someAmount * Time.deltaTime), maxHealth);
having some trouble analyzing your code. shouldn't mathf.max just keep returning maxHealth since it will always be the greater of the two numbers? (you know unless they're equal)
Oh whoops, that was supposed to be $$anonymous$$athf.$$anonymous$$in. I've changed it now!
Answer by Jinxology · Jan 15, 2014 at 12:15 AM
You need to put:
if (healthy) Heal();
inside the Update function:
function Update() {
if (health) Heal();
}
so that it runs every frame. Think of your regeneration rate as the amount healed in 1 second, then simply multiply that by Time.deltaTime (the number of seconds since the last frame).
Think of it this way: If you want to heal 10 HP a second, and the time since the last update (deltaTime) is only .5, then you would only want to heal for 5 HP.
Your answer
Follow this Question
Related Questions
Is there any difference if I duplicate a prefab in Hierarchy or drag it from Project tab? 1 Answer
Scene view doesn't appear to be working 4 Answers
Help with SpringFollowCamera 0 Answers
What are the best tutorial videos to learn just Javascript? 1 Answer
Beginner question about GUI scripting 2 Answers