- Home /
how to run two different function every x seconds based on bool value?
I know I can use invokeRepeating to run function every x seconds. And invokeRepeating should not be in Update or FixedUpdate. It should be in Start or Awake. But in my code it doesn't work. Please look at my code.
public Rigidbody rb;
public float movingSpeed = 200;
public int maxSpeed = 3000;
public bool forwardBackMoving, sideMoving;
void Start()
{
rb = GetComponent<Rigidbody>();
forwardBackMoving = true;
sideMoving = true;
if ((forwardBackMoving == true || sideMoving == true)&&movingSpeed<maxSpeed)
{
InvokeRepeating("increaseSpeed", 5.0f, 5.0f);
}
else if(forwardBackMoving==false&&sideMoving==false)
{
CancelInvoke();
InvokeRepeating("decreaseSpeed", 1.0f, 5.0f);
}
}
This is my code. When one of two bools are set to true, the first one triggers. The second one should be triggered when both booleans are false.
public void keyUpEvent()
{
if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S))
{
forwardBackMoving = false;
}else if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D))
{
sideMoving = false;
}
}
I have this code which changes boolean values. This function is called in FixedUpdate method. Changing bool works without any problem, but the second invokeRepeating never never never wants to trigger even both bools are changed to false. Please can anybody help me?
Answer by Blindleistung · Nov 24, 2019 at 11:44 AM
You are starting one of the two repeating things in start. The condition is only checked once and then this one function, "increase speed" or "decrease speed", are done over and over.
So you need to call one function, like adjustSpeed , and inside this function check the condition.
But I can't make them just as one function because those two functions should have different second parameter. As you see, increaseSpeed has 5.0f as second parameter but decreaseSpeed has 1.0f
Or do you mean call adjustSpeed in Start() and declare bools and do invokeRepeats in adjustSpeed?
I tried adjustSpeed and moved if statements to adjustSpeed and called adjustSpeed inside start()
void Start()
{
rb = GetComponent<Rigidbody>();
forwardBack$$anonymous$$oving = true;
side$$anonymous$$oving = true;
adjustSpeed();
}
void adjustSpeed()
{
if ((forwardBack$$anonymous$$oving == true || side$$anonymous$$oving == true) && movingSpeed < maxSpeed)
{
InvokeRepeating("increaseSpeed", 5.0f, 5.0f);
}
else if (forwardBack$$anonymous$$oving == false && side$$anonymous$$oving == false)
{
CancelInvoke();
InvokeRepeating("decreaseSpeed", 1.0f, 5.0f);
}
}
same result.
Your answer
![](https://koobas.hobune.stream/wayback/20220612215227im_/https://answers.unity.com/themes/thub/images/avi.jpg)