Make a float update its value based on another floats value
To explain, i want a float that will change its value based on the value of another float. Lets say i have a float called Health that is 100f, and i reduce the floats value by 1 every second. By altering the Health float i want to also alter another float called Speed that is originally 1.1f. By reducing the Health float it automatically increases the Speed float by maybe 0.1f. So if the Health float goes from 100 to 99 in value, the Speed float goes up to 1.2f from 1.1f.
Hopefully i explained my issue, otherwise i can explain it more. This will be run during Update() so i need to create a modifier for the Speed float but i cannot add += since it adds every frame, i just want the float to update, so instead of += its just =.
Anyone know how i should think by creating this modifier, or is there a better solution which makes this issue more simple and not so complicated
Thanks
Answer by LK84 · Dec 22, 2016 at 02:35 PM
Just put it in the set accessor of Health:
private float _health;
public float Health
{
get{return _health;}
set
{
_health=value;
Speed=//Whatever you want to enter here;
}
}
Dont i need to specify the amount of health?
private float _health = 100f;
Also in the //Whatever you want to enter here.. Do i write how the Speed variable is being modified? Or the overall new value which Speed needs to be incremented by?
well, you need to initialize it (i.e. in the Start() method):
void Start()
{
_health=100;
Speed=1.1f;
}
Later in the code when you want to change the value of Health you simple write Health=newValue
For the Speed variable you just write whatever logic you want to implement. According to your opening post you want to increase the speed by 0.1 when the Health decreases by 1? Then you can do something like this:
private float _health;
public float Health
{
get{return _health;}
set
{
Speed+=(_health-value)/10;
_health=value;
}
}
ok, and newValue is just any value which i can decide to alter the Health variable with? And as long as i have this code you wrote i can alter the speed variable manually by changing the Health variable? Im pretty unfamiliar with how get set works
EDIT: I managed to make it work now! Thanks a ton!