Hey everyone, i have a problem with InvokeRepeating and variables. I have a float called hunger, and im using an InvokeRepeating to make sure the hunger float decreases every x seconds. This works fine, but what i want is for it to decrease even faster if i hold down a button. Therefor, i obviously use variables, which you can see in my code below. When i press said button, i can see the variables change in the inspector, but the hunger float is actually not decreasing any faster. Is this some sort of limitation w/ InvokeRepeating? Or is something wrong with my code?
C#:
public TextMeshProUGUI hungerText;
public float hunger;
public float hungerDelay;
public float hungerRate;
// Use this for initialization
void Start () {
//hungerDelay = 0.5f;
hunger = 100;
InvokeRepeating ("HungerDecay", hungerDelay, hungerRate);
}
void Update () {
hungerText.text = "" + hunger;
//hungerSpeed -= 0.1f;
if (Input.GetKey (KeyCode.LeftShift)) {
hungerRate = 0.0001f;
}
void HungerDecay()
{
hunger -= 1;
}
}
You need to CancelInvoke and set it again after changing variable.
if (Input.GetKey(KeyCode.LeftShift))
{
if (hungerRate == yourBaseRate) // to make sure instruction will happen only once
{
CancelInvoke("HungerDecay");
hungerRate = 0.0001f;
InvokeRepeating("HungerDecay", hungerDelay, hungerRate);
}
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
CancelInvoke("HungerDecay");
hungerRate = yourBaseRate; // so you can set to "not holding" variable.
InvokeRepeating("HungerDecay", hungerDelay, hungerRate);
}
I would do something like this:
public TextMeshProUGUI hungerText;
public float hunger;
public float hungerDelay;
public float hungerRate;
public float originalHungerRate;
// Use this for initialization
void Start () {
//hungerDelay = 0.5f;
originalHungerRate = hungerRate;
hunger = 100;
InvokeRepeating ("HungerDecay", hungerDelay, hungerRate);
}
void Update () {
hungerText.text = "" + hunger;
//hungerSpeed -= 0.1f;
if (Input.GetKey (KeyCode.LeftShift)) {
CancelInvoke();
hungerRate = 0.0001f;
InvokeRepeating ("HungerDecay", hungerDelay, hungerRate);
} else if (Input.GetKeyUp (KeyCode.LeftShift)) {
CancelInvoke();
hungerRate = originalHungerRate;
InvokeRepeating ("HungerDecay", hungerDelay, hungerRate);
}
void HungerDecay()
{
hunger -= 1;
}
}
I don’t know entirely if this works or not but maybe it will.