- Home /
How do I set a max limit for my health value?
In the game I'm working on, the Main Character can pick up food to recover health (each piece recovers 10 points). I want the max value to be 100, but if I keep picking up food the script adds 10 points to the current value, and I end up having 110, 120, 130 points, etc. I want a script to limit the value so it can't be higher than 100 points.
I've been working on it but I can't seem to find a simple solution; is there an easy way to set a max limit so the points won't be higher than 100?
Thanks.
Answer by smirlianos · Oct 24, 2012 at 08:23 PM
Var health : int = 100;
Function update ()
{
If(health > 100)
{
health = 100;
}
}
Now when your health try to be bigger than 100, it automaticly turns into 100
A good addition to this for future expand-ability would be to replace that 100 with another variable ala: var max_health : int = 100; then check if (health > max_health) health = max_health; this reads nicely and allows you to easily use the same value in other places as needed, and makes it clean and simple to change it if you need to.
Answer by FuzzieLogick · Oct 24, 2012 at 09:07 PM
I'm pretty new to Unity myself but I think this may be able to be solved with a simple if statement. For example:
if(healthPoints >= 100){
healthPoints = 100;
}
You could put this in the Update() function so that it checks on every frame. If I'm right, this should prevent healthPoints from exceeding 100 by setting the value to 100 every time it exceeds that number. Oh, and this is in Javascript :)
Answer by Rati · Oct 24, 2012 at 09:07 PM
or you can check your life only when you pick up the food c# :
void PickUpFood ()
{
health = health + 30;
if(health > 100)
{
health = 100;
}
}
Answer by Thakazax · Mar 30, 2013 at 05:22 PM
You can make it shorter since it's only one line under the if statement.
var health = 100;
function Update ()
{
if(health > 100)
health = 100;
}
Your answer
Follow this Question
Related Questions
Time elapsed between variable change? 1 Answer
Destroy 1 prefab object and changing the color/image 1 Answer
Spinning Pointer that reacts when health drops 0 Answers
Health is set to zero at start of game. 3 Answers
Player Health Not Working? 4 Answers