- Home /
How to Make Two Variables Indirectly Related?
I'm working on a fighting game that uses an energy bar and a health bar. The amount energy you gain is dependent on the amount of health you lose. How would you say that when your health goes down by, let's say 32, so will your energy by the same amount? Any help is appreciated.
Comment
Best Answer
Answer by malkere · Jul 02, 2014 at 03:35 AM
you can just say energy +32 when you say health -32 make a void that you use whenever you subtract health:
public void HitPlayer(int amount){
health = health - amount;
energy = energy + amount;
}
I use Java but I get the idea. It's so simple... I can't believe I never thought of it! Thanks!
Answer by Duss · Jul 02, 2014 at 03:54 AM
You could make a property with your health variable so that every time the "health" property is set, the energy is set at the same time:
private float _energy;
private float _health;
public float health {
get {
return _health;
}
set {
float oriHealth = _health;
_health = value;
_energy -= (oriHealth - _health); // The energy goes down the same amount as the health.
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613152958im_/https://answers.unity.com/themes/thub/images/avi.jpg)